简体   繁体   English

在 Python 中的文本文件的特定行中附加数据?

[英]appending a data in a specific line of a text file in Python?

Let's say I have this textfile: date.txt.假设我有这个文本文件:date.txt。 month|day|year月|日|年

January|20|2014
February|10|
March|5|2013

I want to put 2012 after February|10|.我想把2012放在二月|10|之后。 how can i do that?我怎样才能做到这一点?

You need to read the file into memory, modify the desired line and write back the file.您需要将文件读入内存,修改所需的行并写回文件。

temp = open('temp', 'wb')
with open('date.txt', 'r') as f:
    for line in f:
        if line.startswith('February'):
            line = line.strip() + '2012\n'
        temp.write(line)
temp.close()
shutils.move('temp', 'data.txt')

If you don't want to use a temporary file:如果您不想使用临时文件:

with open('date.txt', 'r+') as f: #r+ does the work of rw
    lines = f.readlines()
    for i, line in enumerate(lines):
        if line.startswith('February'):
            lines[i] = lines[i].strip() + '2012\n'
    f.seek(0)
    for line in lines:
        f.write(line)

You can use the csv module, for example:您可以使用csv模块,例如:

import csv

data = [
    "January|20|2014",
    "February|10|",
    "March|5|2013"
]

reader = csv.reader(data, delimiter="|")
for line in reader:
    line = [i if i != "" else "2012" for i in line]
    print(line)

Please note: csv.reader() take as argument any iterable object.请注意: csv.reader()将任何可迭代对象作为参数。 So, you can easily pass it a file object因此,您可以轻松地将文件对象传递给它

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

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