How do you replace a specific line of a file with python? - python

line_row = -1
file = open(file_path, 'r')
for number_of_lines in file:
line_row = line_row + 1
if '1234' in number_of_lines:
lines = file.readlines()
line = lines[line_row]
print(lines)
lines[line_row] = 'hello'
file = open(file_path, "w")
file.writelines(lines)
file.close()
When I run this, it will delete everything that is before the nth line. I want it to replace only the nth line. can you help me?

try this, using enumerate
with open(file_path, 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if "some text" in line:
lines[i] = "updated text"
with open(file_path, "w") as f:
f.writelines(lines)

Related

Append String to each line of .txt file in python?

I want to append some text to every line in my file
Here is my code
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :
with open(filepath, 'r') as f: # load file
lines = f.read().splitlines() # read lines
with open('new_file.txt', 'w') as f:
f.write('\n'.join([line + '#' for line in lines])) # write lines with '#' appended
I'll assume the file is small enough to keep two copies of it in memory:
filepath = 'hole.txt'
with open(filepath, 'r') as f:
original_lines = f.readlines()
new_lines = [line.strip() + "#\n" for line in original_lines]
with open(filepath, 'w') as f:
f.writelines(new_lines)
First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.
Then, the last line overwrites the file with the new, modified lines.
does this help?
inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"
with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
for line in inFile:
outFile.write(stringToAPpend+line)

I need to search a string in data file. but the string is written in another file

I have key words to be search in one file let say abc.txt and in another file I have my data, def.txt.
I want a code in python to find key words written in abc.txt, in def.txt and if present, print those line in a new file.
Thank you.
I tried writing a code but it didn't work.
following is the code I write.
f = open('/home/vivek/Documents/abc.txt')
f1 = open('output.txt', 'a')
f2 = open('/home/vivek/Documents/def.txt', 'r')
# doIHaveToCopyTheLine=False
for line in f.readlines():
if f2 in line:
f1.write(line)
f1.close()
f.close()
f2.close()
Load the keywords into a list then you can check the other file line-by-line, and write to outfile as you find keywords in the line.
with open('/path/to/keywords.txt') as f:
keywords = set(line.strip() for line in f) # assuming words are separated by line
with open('/path/to/search_me.txt') as f, open('/path/to/outfile.txt', 'w') as outfile:
for line in f:
if any(kw in line for kw in keywords):
outfile.write(line)
You should record all the words in abc.txt use a set and then search them in def.txt
word_set = set()
with open('/home/vivek/Documents/abc.txt') as f:
for line in f:
word_set.add(line.strip())
f1 = open('output.txt', 'a')
with open('/home/vivek/Documents/def.txt') as f:
for line in f:
find = False
for word in word_set:
if word in line:
find = True
break
if find:
f1.write(line)
f1.close()
You can try this code:
with open("keyword.txt", "r") as keyword_file:
keywords = keyword_file.read().strip()
keywords = keywords.split()
with open("data.txt", "r") as data_file, open("output.txt", "w") as output_file:
for line in data_file.readlines():
line = line.strip()
for word in keywords:
if line.find(word) != -1:
print line
output_file.writelines(line + '\n')
break
In addition to sytech's answer you may try this:
with open('def.txt') as kw_obj, open('abc.txt') as in_obj:
keywords = set(kw_obj.read().split())
in_lines = in_obj.readlines()
match_lines = [line for keyword in keywords for line in in_lines if keyword in line]
if match_lines:
with open('out.txt', 'w') as out:
out.write(''.join(match_lines))

Python replace value in text file

I'm trying to replace a value in a specific line in a text file.
My text file contains count of the searchterm, searchterm & date and time
Text file:
MemTotal,5,2016-07-30 12:02:33,781
model name,3,2016-07-30 13:37:59,074
model,3,2016-07-30 15:39:59,075
How can I replace for example the count of the searchterm for line 2 (model name,3,2016-07-30 13:37:59,074)?
This is what I have already:
f = open('file.log','r')
filedata = f.read()
f.close()
newdata = filedata.replace("2", "3")
f = open('file.log', 'w')
f.write(newdata)
f.close()
It replace all values 2.
You have to change three things in your code to get the job done:
Read the file using readlines.
filedata = f.readlines()
Modify the line you want to change (keep in mind that Python indices start at 0 and don't forget to add a newline character \n at the end of the string):
filedata[1] = 'new count,new search term,new date and time\n'
Save the file using a for loop:
for line in filedata:
f.write(line)
Here is the full code (notice I used the with context manager to open/close the file):
with open('file.log', 'r') as f:
filedata = f.readlines()
filedata[1] = 'new count,new search term,new date and time\n'
with open('file.log', 'w') as f:
for line in filedata:
f.write(line)
My solution:
count = 0
line_number = 0
replace = ""
f = open('examen.log','r')
term = "MemTotal"
for line in f.read().split('\n'):
if term in line:
replace= line.replace("5", "25", 1)
line_number = count
count = count + 1
print line_number
f.close()
f = open('examen.log','r')
filedata = f.readlines()
f.close()
filedata[line_number]=replace+'\n'
print filedata[line_number]
print filedata
f = open('examen.log','w')
for line in filedata:
f.write(line)
f.close()
You only need to define the searchterm & the replace value

Need to delete a specific word from a specific line in Python

My textfile is like this:
"A rainbow has seven colors.
A rainbow rises just after the rainfall."
I want the word "rainbow" to be deleted from the 1st line but not from the second line and in the new file all the lines to be printed as it is without the rainbow in the first line. With a code like this:
infile = "old.txt"
outfile = "new.txt"
delete_word = ["rainbow"]
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in delete_word:
if 'has' in line:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
I am getting only the first line printed without 'rainbow'.
infile = "old.txt"
outfile = "new.txt"
delete_word = "rainbow"
with open(infile, "r") as fin, open(outfile, "a") as fout:
for line in fin:
for word == delete_word:
line = line.replace(word, "")
fout.write(line)
Try:
infile = "old.txt"
outfile = "new.txt"
delete_word = ["rainbow"]
lines = [1] #List of lines you want to delete the word from
fin = open(infile)
fout = open(outfile, "w+")
line_count = 0
for line in fin:
line_count += 1
for word in line.split():
if word in delete_word and line_count in lines:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()

Python: Filter in File I/O

I'm trying to take out the strings "a" and "b" from a document. Here's what I am doing but it's not working because I can't use replace in a list.
def filter_ab(filename):
fileRef=open(filename)
file_list=fileRef.readlines()
filter="ab"
for k in file_list:
for j in k:
if j in filter:
file_list=file_list.replace(j,"")
Can you use something like this:
f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
f2.write(line.replace('a', '').replace('b', ''))
f1.close()
f2.close()
Just use this:
def filter_ab(filename):
lines = []
with open(filename, "r") as fh:
for line in fh.readlines():
line = line.replace("a", "")
line = line.replace("b", "")
lines.append(line)
with open(filename, "w") as fh:
for line in lines:
fh.write(line)
str.translate is actually quite convenient for something like this
with open('file1.txt', 'r') as f1, open('file2.txt', 'w') as f2:
for line in f1:
f2.write(line.translate(None, 'ab'))

Categories

Resources