在Python中将数据附加到文本文件的特定行中? [英] appending a data in a specific line of a text file in Python?
本文介绍了在Python中将数据附加到文本文件的特定行中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说我有这个文本文件:date.txt.月|日|年
Let's say I have this textfile: date.txt. month|day|year
January|20|2014
February|10|
March|5|2013
我想将2012年2月| 10 |之后.我该怎么办?
I want to put 2012 after February|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)
这篇关于在Python中将数据附加到文本文件的特定行中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文