I am a newbie to python and trying to read file line by line and append a word at the end of each line. The "print line" shows that the required word has got appended but the same thing not written back to the file as required . Appreciate your help.
#!/usr/bin/python
f=open('test1', 'r+')
for line in f:
line=line.strip("\n")
line=line +" " + 'test2'
print line
f.write(line)
f.close()
Generally speaking, reading/writing a file at the same time is a really horribly difficult thing to get right. Usually, you'll read from one file and write to a different file (possibly in memory). An in-memory implementation would be something like:
with open('test1', 'r') as fin:
lines = [line.strip('\n') + ' test2\n' for line in fin]
with open('test1', 'w') as fout:
fout.writelines(lines)
Notice that I read all the file's data into memory in the first with block. In the second with block, I write all that data back out to a new file (which conveniently has the same name as the old file effectively overwriting the old). Of course, if memory is a problem, you can read a line and then write a line to a new file (with a different name). After you've closed and flushed both files, then you can use shutil.move to rename the new file so that you overwrite the old one.
#mgilson's answer is very well, and just a little error is the lines in the end of lines = [line.strip('\n') + ' test2\n' for line in lines] should be fin.
The code given by mgilson is great! However, the function you request is not possible if you read and append at the same time.
I am too new to python.
So, I find myself more comfort in the following syntax.
# read in
f = open('test1', 'r')
newlines = []
for line in f:
newline = line.strip("\n") + " " + 'test2' + "\n"
newlines.append(newline)
print newline,
f.close()
# overwrite the same file
f = open('test1', 'w')
f.writelines(newlines)
f.close()
mgilson's code is slightly wrong. Corrected:
with open("test1", "r") as f:
new_contents = [line.strip() + "test2" for line in f.readlines()]
with open("test1", "w") as f:
f.write("\n".join(new_contents))
Related
So I have a file with some lines of text:
here's a sentence
look! another one
here's a third one too
and another one
one more
and I have some code that takes the each line and puts it into a list and then reverses the order of the whole list but now I don't know how to write each line back to the file and delete the existing ones in the text file.
Also when I run this code:
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
everything works and the line order is reversed, but when I run this code:
text_file = open(file_name, "w")
file_lines = open(file_name).readlines()
print(file_lines)
file_lines.reverse()
print(file_lines)
for line in file_lines:
text_file.write(line)
it prints empty lists for some reason.
You can fix it by doing just 2 little changes in your script.
Use \r+ in place of \w+
Before performing write operation, place file position indicator to the beginning
text_file.seek(0)
» rw_file.txt - before operation
here's a sentence
look! another one
here's a third one too
and another one
one more
Below is your modified script to reverse the content of file (It worked).
def reverseFile(file_name):
text_file = open(file_name, "r+") # Do not use 'w+', it will erase your file content
file_lines = [line.rstrip('\n') for line in text_file.readlines()]
file_lines.reverse()
print(file_lines)
text_file.seek(0) # Place file position indicator at beginning
for line_item in file_lines:
text_file.write(line_item+"\n")
reverseFile("rw_file.txt")
» rw_file.txt - after operation
one more
and another one
here's a third one too
look! another one
here's a sentence
If you open the file in 'w' mode, the file is erased. From the docs:
'w' for only writing (an existing file with the same name will be
erased)
You should also use the with keyword:
It is good practice to use the with keyword when dealing with file
objects. The advantage is that the file is properly closed after its
suite finishes...
I would recommend you read the contents of the file first, process that data, and then write:
def reverseFile(file_name):
with open(file_name, 'r') as f:
file_lines = [line.rstrip('\n') for line in f.readlines()]
file_lines.reverse()
with open(file_name, "w") as f:
for line in file_lines:
f.write(line + '\n')
reverseFile('text_lines.txt')
I am trying to create a script that will take each line in my text file which includes one rule name in each of them. The first script I created worked (finished) but would delete everything in the file. I have been googling for past hour or so trying to take examples and apply them on my own but keep failing. The current script is as follows.
with open('TDAppendlist.txt', 'w') as file:
for line in file:
s = ('""')
seq = (file)
s.join(seq)
with open('TDAppendlist.txt') as file:
line = file.readlines()
for line in file:
line.join('"' + line + '"')
Neither of them are working. Could someone please point me in the correct direction? Thank you all for reading.
First, we'll read all the lines of the file into a list, then we can change them, and finally write them back to the file.
with open('TDAppendlist.txt') as file:
lines = list(file)
with open('TDAppendlist.txt', 'w') as file:
file.write('\n'.join(['"{}"'.format(line.rstrip('\n')) for line in lines]))
That last line can be written out to be more clear
lines = (line.rstrip('\n') for line in lines)
lines = ('"{}"'.format(line) for line in lines)
lines = '\n'.join(lines)
file.write(lines)
This produces an output file TDAppendlist_out that is just like the input, but with quotes surrounding the lines:
with open('TDAppendlist.txt', 'r') as f:
with open('TDAppendlist_out.txt', 'w') as f_out:
for line in f:
f_out.write('\"{}\"'.format(line))
This keeps the input file intact as is should you need it later, and avoids putting everything in the input file into memory all at once.
How to update existing line of file in Python?
Example: I want to update session.xml to sesion-config.xml without writing new line.
Input A.txt:
fix-config = session.xml
Expected output A.txt:
fix-config = session-config.xml
You can't mutate lines in a text file - you have to write an entirely new line, which, if not at the end of a file, requires rewriting all the rest.
The simplest way to do this is to store the file in a list, process it, and create a new file:
with open('A.txt') as f:
l = list(f)
with open('A.txt', 'w') as output:
for line in l:
if line.startswith('fix-config'):
output.write('fix-config = session-config.xml\n')
else:
output.write(line)
The solution #TigerhawkT3 suggested would work great for small/medium files.
For extremely large files loading the entire file into memory might not be possible, and then you would want to process each line separately.
Something along these lines should work:
import shutil
with open('A.txt') as input_file:
with open('temp.txt', 'w') as temp_file:
for l in input_file:
if l.startswith('fix-config'):
temp_file.write('fix-config = session-config.xml\n')
else:
temp_file.write(l)
shutil.move('temp.txt', 'A.txt')
I have to read each line in a file with indent.
Here's what I have, but it's not working...
f = open("filename.txt", "r")
print("\t" + f.read())
The indent only applies to the first line.
The .read() method returns the entire contents of a file. The method you want is .readlines(), which returns a list containing each line separately. The code you want looks more like this:
f = open("filename.txt")
lines = f.readlines()
for line in lines:
print("\t" + line)
Additionally, open() reads by default, so including 'r' isn't necessary. Enjoy coding!
I am new to Python programming...
I have a .txt file....... It looks like..
0,Salary,14000
0,Bonus,5000
0,gift,6000
I want to to replace the first '0' value to '1' in each line. How can I do this? Any one can help me.... With sample code..
Thanks in advance.
Nimmyliji
I know that you're asking about Python, but forgive me for suggesting that perhaps a different tool is better for the job. :) It's a one-liner via sed:
sed 's/^0,/1,/' yourtextfile.txt > output.txt
This applies the regex /^0,/ (which matches any 0, that occurs at the beginning of a line) to each line and replaces the matched text with 1, instead. The output is directed into the file output.txt specified.
inFile = open("old.txt", "r")
outFile = open("new.txt", "w")
for line in inFile:
outFile.write(",".join(["1"] + (line.split(","))[1:]))
inFile.close()
outFile.close()
If you would like something more general, take a look to Python csv module. It contains utilities for processing comma-separated values (abbreviated as csv) in files. But it can work with arbitrary delimiter, not only comma. So as you sample is obviously a csv file, you can use it as follows:
import csv
reader = csv.reader(open("old.txt"))
writer = csv.writer(open("new.txt", "w"))
writer.writerows(["1"] + line[1:] for line in reader)
To overwrite original file with new one:
import os
os.remove("old.txt")
os.rename("new.txt", "old.txt")
I think that writing to new file and then renaming it is more fault-tolerant and less likely corrupt your data than direct overwriting of source file. Imagine, that your program raised an exception while source file was already read to memory and reopened for writing. So you would lose original data and your new data wouldn't be saved because of program crash. In my case, I only lose new data while preserving original.
o=open("output.txt","w")
for line in open("file"):
s=line.split(",")
s[0]="1"
o.write(','.join(s))
o.close()
Or you can use fileinput with in place edit
import fileinput
for line in fileinput.FileInput("file",inplace=1):
s=line.split(",")
s[0]="1"
print ','.join(s)
f = open(filepath,'r')
data = f.readlines()
f.close()
edited = []
for line in data:
edited.append( '1'+line[1:] )
f = open(filepath,'w')
f.writelines(edited)
f.flush()
f.close()
Or in Python 2.5+:
with open(filepath,'r') as f:
data = f.readlines()
with open(outfilepath, 'w') as f:
for line in data:
f.write( '1' + line[1:] )
This should do it. I wouldn't recommend it for a truly big file though ;-)
What is going on (ex 1):
1: Open the file in read mode
2,3: Read all the lines into a list (each line is a separate index) and close the file.
4,5,6: Iterate over the list constructing a new list where each line has the first character replaced by a 1. The line[1:] slices the string from index 1 onward. We concatenate the 1 with the truncated list.
7,8,9: Reopen the file in write mode, write the list to the file (overwrite), flush the buffer, and close the file handle.
In Ex. 2:
I use the with statement that lets the file handle closing itself, but do essentially the same thing.