简体   繁体   English

在python中的文本文件中编辑特定行

[英]Edit a specific line in a text file in python

I want to edit a line in a text file in python. 我想在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). 我通常使用“ xreadlines()”来操纵文本文件(例如1GB文件)。 For example, if I want to shift all the dates in the beginning of line, the following example is shown with Python code. 例如,如果我想将所有日期都移到行首,则下面的示例显示为Python代码。

inputfile: inputfile.txt inputfile:inputfile.txt

$Name1 $ Name1
Name1 xx xx 名称1 xx xx
Date WATER Category 日期水类别
19620701 100 a1 19620701 100 a1
19630801 200 b1 19630801 200 b1
19630901 150 c1 19630901 150 c1
$Name2 $ Name2
Name2 xx xx 名称2 xx xx
Date WATER Category 日期水类别
19620701 200 a2 19620701 200 a2
19630801 100 b2 19630801 100平方米
19630901 300 c2 19630901 300厘米2
... ...

outFile:Outfile.txt. outFile:Outfile.txt。 Even with the high-volume txt file, the program only takes 20s to finish the run. 即使使用大量txt文件,该程序也只需20秒即可完成运行。

Name1 Name1 xx xx Date 名称1名称1 xx xx日期
WATER Category 水类别
19620601 100 a1 19620601 100 a1
19630701 200 b1 19630701 200 b1
19630801 150 c1 19630801 150 c1
Name2 名称2
Name2 xx xx 名称2 xx xx
Date WATER Category 日期水类别
19620601 200 a2 19620601 200 a2
19630701 100 b2 19630701 100平方米
19630801 300 c2 19630801 300毫升
... ...

Python code: Python代码:

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: 我喜欢使用fileinput模块来编辑文件,如下所示:

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命令,例如:

python myprogram.py data.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM