Delete a variable piece of text from every line in textfile - replace

I have a .txt file full with lines like:
username:password:*email*:email_address, where *email* is a fixed word throughout the file.
I wanted to delete everything after the first : and before the second :, in other words, delete the passwords and have only username:*email*:email_address.
Can anyone help me? Thanks

You could write a Python script like this:
with open('file.txt') as f:
for line in f.readlines():
fields = line.split(':')
del fields[1]
print ':'.join(fields),
and redirect the output to a new file.

Related

How to replace and save a word in text file using regular expression in python

Here is my program I want to replace a word to another word in a text file using a regular expression but I am not able to save those words in the text file. Can anyone, please help me to save a file. Thank you in advance.
Given below is my code:
import re
with open("c:\Users\Desktop\hh.txt","r+") as f:
for i in f.readlines():
content=re.sub("hai","welcome",i)
#after replace how can i save these words in text file again
A simple approach for small files is to do your reading and writing separately.
import re
path = 'hh.txt'
with open(path, "r") as f:
oldlines = f.readlines()
newlines = []
for line in oldlines:
newlines.append(re.sub("hai", "welcome", line))
with open(path, "w") as f:
f.writelines(newlines)
If you're dealing with huge files, I suggest you write to a temporary file while reading from your input file. Then do a file delete then a file rename.

Python - using raw_input() to search a text document

I am trying to write a simple script that a user can enter what he/she wants to search in a specified txt file. If the word they searching is found then print it to a new text file. This is what I got so far.
import re
import os
os.chdir("C:\Python 2016 Training")
patterns = open("rtr.txt", "r")
what_directory_am_i_in = os.getcwd()
print what_directory_am_i_in
search = raw_input("What you looking for? ")
for line in patterns:
re.findall("(.*)search(.*)", line)
fo = open("test", "wb")
fo.write(line)
fo.close
This successfully creates a file called test, but the output is nothing close to what word was entered into the search variable.
Any advice appreciated.
First of all, you have not read a file
patterns = open("rtr.txt", "r")
this is a file object and not the content of file, to read the file contents you need to use
patterns.readlines()
secondly, re.findall returns a list of matched strings, so you would want to store that. You regex is also not correct as pointed by Hani, It should be
matched = re.findall("(.*)" + search + "(.*)", line)
rather it should be :
if you want the complete line
matched = re.findall(".*" + search + ".*", line)
or simply
matched = line if search in line else None
Thirdly, you don't need to keep opening your output file in the for loop. You are overwriting your file everytime in the loop so it will capture only the last result. Also remember to call the close method on the files.
Hope this helps
you are searching here for all lines that has "search" word in it
you need to get the lines that has the text you entered in the shell
so change this line
re.findall("(.*)search(.*)", line)
to
re.findall("(.*)"+search+"(.*)", line)

Replace the whole string if it contains specific letters/character

Replace the whole string if it contains specific letters/character…
I have a text file (myFile.txt) that contains multiple lines, for example:
The hotdog
The goal
The goat
What I want to do is the following:
If any word/string in the file contains the characters 'go' then, replace it with a brand new word/string ("boat"), so the output would look like this:
The hotdog
The boat
The boat
How can I accomplish this in Python 2.7?
It sounds like you want something like this:
with open('myFile.txt', 'r+') as word_bank:
new_lines = []
for line in word_bank:
new_line = []
for word in line.strip().split():
if 'go' in word:
new_line.append('boat')
else:
new_line.append(word)
new_lines.append('%s\n' % ' '.join(new_line))
word_bank.truncate(0)
word_bank.seek(0)
word_bank.writelines(new_lines)
Open the file for reading and writing, iterate through it splitting each line into component words and looking for instances of 'go' to replace. Keep in list because you do not want to modify something you're iterating over. You will have a bad time. Once constructed, truncate the file (erase it) and write what you came up with. Notice I switched to sticking an explicit '\n' on the end because writelines will not do that for you.

How to use the Raw_Input/User Input to replace certain lines of Text in a Text File

Currently I have a text File labelled Test1.txt, where there are lines of Text written like so:
Question 2) Delete This
a) Sample Text
b) Sample Text
I would like to replace the 'Delete This' segment of the seventh line with a User Input.
Note; The line of text: [Question 2) Delete This] ,is the seventh line.
How would someone replace a certain part of a line of text, by using the raw_input?
This is the code so far
f = open('Test1.txt', 'r+')
f.write(raw_input("Start Writing:\n"))
f.close()
This successfully writes the User Input onto the file Test1.txt. Yet it obviously just writes it onto the first line.
I am not sure how to replace the 'Delete This' with the User Input.
I would like to know how to replace a section of a line with the User Input.
For example if the User Enters: abc
Then the text file would read:
Question 2) abc #rather than Delete This
a) Sample Text
b) Sample Text
Very New to Python, so any explanation on any code would be Much Appreciated!
Thanks
Potential Duplicate: Writing multiple lines to a textfile by taking input in python?

Importing a file, then turning it into a list of strings?

I'm trying to import a dictionary of words to use in a word game. The file I'm importing is a .rtf file with a single word on each line. I'd like to turn each line into an element of one large single list. The name of the file is "TextTwistDictionary.rtf". How would I go about doing this?
list_words = []
with open('TextTwistDictionary.rtf') as f:
for line in f: # read every line in the file
list_words.append(line) # append each line to the list
print list_words
with open(fileName) as fileHandle:
dictionary = fileHandle.readlines()