I want to edit a line in a text file in python.
I have a text file
name:
address:
age:
I need to add things to some specific fileds of the above file. Basically fill some of the fields.
ex: The output should be
name:
address:xxx
age:20
I normally use "xreadlines()" to manipulate the text file (eg. 1GB file). For example, if I want to shift all the dates in the beginning of line, the following example is shown with Python code.
$Name1
Name1 xx xx
Date WATER Category
19620701 100 a1
19630801 200 b1
19630901 150 c1
$Name2
Name2 xx xx
Date WATER Category
19620701 200 a2
19630801 100 b2
19630901 300 c2
...
outFile:Outfile.txt. Even with the high-volume txt file, the program only takes 20s to finish the run.
Name1 Name1 xx xx Date
WATER Category
19620601 100 a1
19630701 200 b1
19630801 150 c1
Name2
Name2 xx xx
Date WATER Category
19620601 200 a2
19630701 100 b2
19630801 300 c2
...
Python code:
inputFile=open('inputfile.txt','w')
OutFile=open('Outfile.txt'+,'w')
date0=date_init='19620601'
lines1=open(inputFile,'r').xreadlines()
for line in lines1:
line_date=line[0:8] #Take the 1st 8 char,'19620701'
if line_date.isdigit():
OutFile.write(date0+line[8:])
date0=line_date
else:
date0=date_init #Start from the first date
OutFile.write(line)
open(inputFile,'r').close()
OutFile.close()
I like to use the fileinput
module to edit files in place, like so:
import fileinput
import sys
for line in fileinput.input(inplace=True):
# Whatever is written to stdout or with print replaces
# the current line
if line.startswith("address:"):
print("address:xxx")
elif line.startswith("age:"):
print("age:20")
else:
sys.stdout.write(line)
Simply pass the filename as an argument to the python command, for example:
python myprogram.py data.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.