Python 将文本添加到文件的第一行
我有一行Python代码,生成了我想要的东西。代码是:Python 将文本添加到文件的第一行,python,Python,我有一行Python代码,生成了我想要的东西。代码是: os.system('cat {0}|egrep {1} > file.txt' .format(full,epoch)) 并生成了一个包含以下内容的文件: 3 321.000 53420.7046629965511 0.299 0.00000 3 325.000 53420.7046629860714 0.270
os.system('cat {0}|egrep {1} > file.txt' .format(full,epoch))
并生成了一个包含以下内容的文件:
3 321.000 53420.7046629965511 0.299 0.00000
3 325.000 53420.7046629860714 0.270 0.00000
3 329.000 53420.7046629846442 0.334 0.00000
3 333.000 53420.7046629918374 0.280 0.00000
然后我只想调整代码,使其顶部显示为“文本1”,因此我尝试了脑海中出现的第一件事,并将代码更改为:
h = open('file.txt','w')
h.write('MODE 2\n')
os.system('cat {0}|egrep {1} > file.txt' .format(full,epoch))
当我这样做时,我得到了输出:
TEXT 1
317.000 54519.6975201839344 0.627 0.00000
3 321.000 54519.6975202038578 0.655 0.00000
3 325.000 54519.6975201934045 0.608 0.00000
3 329.000 54519.6975201919911 0.612 0.00000
i、 e.“文本1”后的第一行不正确,缺少第一个“3”。有人能告诉我我做错了什么吗?也许还有更好的方法来完成这个简单的任务
谢谢。您使用python打开一个文件句柄,对其进行写入,但python将其留给操作系统来执行刷新等操作。根据设计,如果您希望在写入其他内容之前将某个内容写入文件,则需要手动执行该操作(事实上,您需要
刷新和fsync
)
另一个注意事项是:>file.txt
创建了一个新文件,而您可能希望附加-它将被写为>file.txt
。简而言之:您的代码可能像您所想的那样更不确定
另一种方法是使用模块,因为您已经处于shell级别:
您可以按自己的方式调用grep,也可以使用subprocess.call(),这是我首选的方法
方法1:使用os.system()
此方法将在调用egrep
之前在文本1前面加上前缀。请注意,您不需要cat
方法2:使用subprocess.call()
这是我的首选方法,有几个原因:您可以更好地控制输出文件,例如在打开失败时处理异常的能力。查看此帖子:
from subprocess import call
sts = call("echo 'TEXT 1' > file.txt", shell=True)
sts = call("cat {0}|egrep {1} >> file.txt".format(full,epoch), shell=True)
os.system('echo TEXT 1 >file.txt; egrep {1} {0} >> file.txt'.format(full, epoch))
with open('out.txt', 'wb') as output_file:
output_file.write('TEXT 1\n')
output_file.flush()
subprocess.call(['egrep', epoch, full], stdout=output_file)