【问题标题】:How would I write separate words to a file, with words between them?我如何将单独的单词写入文件,它们之间有单词?
【发布时间】:2022-10-26 00:05:19
【问题描述】:
我正在尝试使用 python3 编写从words.txt 到newfile.txt 的单词,格式如下:
单词.txt:
Hello
I
am
a
file
我希望在words.txt 中的每个新单词之间添加单词Morning,在一个名为newfile.txt 的新文件中。
所以newfile.txt 应该是这样的:
Hello
Morning
I
Morning
Am
Morning
A
Morning
File
有谁知道如何做到这一点?
抱歉措辞不好,
后门布鲁
【问题讨论】:
标签:
python
python-3.x
file
append
【解决方案1】:
为避免为大文件占用主内存,您需要随时插入额外的字符串。这并不难,只是有点棘手,以确保它们只在现有行之间,而不是在开头或结尾:
# Open both files
with open('words.txt') as inf, open('newfile.txt', 'w') as outf:
outf.write(next(inf)) # Copy over first line without preceding "Morning"
for line in inf: # Lazily pull remaining lines from infile one by one
outf.write("Morning
") # Write the in-between "Morning" before each new line
outf.write(line) # Write pre-existing line