[英]Python: truncate txt file before writing
I have a set of .txt files (12) that I want to read and write to 3 output .txt files (so each output will have text from all 12 files).我有一组 .txt 文件 (12),我想读取和写入 3 个输出 .txt 文件(因此每个输出都将包含来自所有 12 个文件的文本)。
I accomplish this with the following code, BUT the files do not overwrite what is already there, but append the text.我使用以下代码完成此操作,但文件不会覆盖已经存在的内容,而是附加文本。 I realize this may be due to me using "a" as append, but if I use "w", only the first document of my 12 gets written to each output.
我意识到这可能是由于我使用“a”作为附加,但是如果我使用“w”,则只有我的 12 个文档中的第一个文档被写入每个输出。
The "truncate()" method seems to have no effect. “truncate()”方法似乎没有效果。
def WriteFiles():
# import library
import glob
# read file names
txt_files = glob.glob('input/*.txt')
output_files = glob.glob('output*')
# loop trough outputs & files and append
for index_out, output in enumerate(output_files):
for index_in, file in enumerate(txt_files):
with open(file, 'r+') as f, open(output, 'a') as o:
print('Writing input {} to output {}'.format(index_in, index_out))
o.truncate()
o.write(f.read())
You could simply open
the output file earlier, in the first for
loop.您可以更早地在第一个
for
循环中open
输出文件。 Eg例如
for index_out, output in enumerate(output_files):
with open(output, 'w') as o:
for index_in, file in enumerate(txt_files):
with open(file, 'r+') as f:
print('Writing input {} to output {}'.format(index_in, index_out))
o.write(f.read())
This will only open and truncate each output file once, before the second for
loop starts, and the file
object will look after the current position in the output file.这只会在第二个
for
循环开始之前打开并截断每个输出文件一次,并且file
对象将查看输出文件中的当前位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.