How to replace text in a txt file with python? - python-2.7

I'm trying to replace text in a .txt file using a .py script. Here's what i have so far:
docname=raw_input("Enter a document name: ")
fo=open(docname, 'r+')
string=fo.read()
replace=raw_input("Enter what you want to replace: ")
replacewith=raw_input("Enter what you want to replace it with: ")
out=string.replace(replace,replacewith)
fo.write(out);
fo.close()
print "Check the document!"
closeInput = raw_input("Press ENTER to exit")
I have a txt file called "test.txt" (in the same directory as the .py script). When I enter "test.txt", it asks what I want to replace, as expected. When I fill out that, it asks for what I want to replace it with.
I fill out that, and the program closes. No "Check the document!" or anything. And worst of all, it doesn't replace it with the second string.
Please help!

you have 2 possibilities:
if you want to open the file just once, you should reset the
position of the stream with fo.seek(0)
you can close and reopen the file with fo = open(docname, 'w')
The first option has one problem: if the replace-text is shorter than the original-text, some text will be left over at the end.
To illustrate what I'm talking of:
You have the text '12345' and want to replace '12' with 'a', then the resulting file would
contain 'a3455'

Related

Python Search File For Specific Word And Find Exact Match And Print Line

I wrote a script to print the lines containing a specific word from a bible txt file.The problem is i couldn't get the exact word with the line instead it prints all variations of the word.
For eg. if i search for "am" it prints sentences with words containing "lame","name" etc.
Instead i want it to print only the sentences with "am" only
i.e, "I am your saviour", "Here I am" etc
Here is the code i use:
import re
text = raw_input("enter text to be searched:")
shakes = open("bible.txt", "r")
for line in shakes:
if re.match('(.+)' +text+ '(.+)', line):
print line
This is another approach to take to complete your task, it may be helpful although it doesn't follow your current approach very much.
The test.txt file I fed as input had four sentences:
This is a special cat. And this is a special dog. That's an average cat. But better than that loud dog.
When you run the program, include the text file. In command line, that'd look something like:
python file.py test.txt
This is the accompanying file.py:
import fileinput
key = raw_input("Please enter the word you with to search for: ")
#print "You've selected: ", key, " as you're key-word."
with open('test.txt') as f:
content = str(f.readlines())
#print "This is the CONTENT", content
list_of_sentences = content.split(".")
for sentence in list_of_sentences:
words = sentence.split(" ")
for word in words:
if word == key:
print sentence
For the keyword "cat", this returns:
That is a special cat
That's an average cat
(note the periods are no longer there).
I think if you, in the strings outside text, put spaces like this:
'(.+) ' + text + ' (.+)'
That would do the trick, if I correctly understand what is going on in the code.
re.findall may be useful in this case:
print re.findall(r"([^.]*?" + text + "[^.]*\.)", shakes.read())
Or even without regex:
print [sentence + '.' for sentence in shakes.split('.') if text in sentence]
reading this text file:
I am your saviour. Here I am. Another sentence.
Second line.
Last line. One more sentence. I am done.
both give same results:
['I am your saviour.', ' Here I am.', ' I am done.']

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.

Change values in Python file (tab-delimited list)

I have read a *.INP file into Python. Here is the code I used:
import csv
r = csv.reader(open('T_JAC.INP')) # Here your csv file
lines = [l for l in r]
print lines[23]
print lines[26]
The first print statement produces ['9E21\t\texthere (text) text alphabets text alphanumeric'].
The second print statement produces ['4E15\t\texthere (text) text alphabets text alphanumeric'].
I need to change the numbers 7E21 and 4E15. I need to change them to values from a list fil_replace = [9E21,6E15].i.e. I need to replace 7E21 to 9E21 and I need to change 4E21 to 6E21.
Is there a way to replace these numbers?
Something with str.replace should work (as long as you read r in as a string), albeit not the most efficient solution:
r.replace('7E21', '9E21')
file = open('YAC.IN', 'w')
file.write(r)
file.close()
If you're looking for a way to just replace the values 'in place' in the file unfortunately it's not possible. The entire file has to be read in, modified, then re-written.

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?