我正在嘗試使用 python3 撰寫單詞words.txt,newfile.txt格式如下:
單詞.txt:
Hello
I
am
a
file
我希望Morning在每個新單詞之間添加單詞words.txt,在一個名為newfile.txt.
所以newfile.txt應該是這樣的:
Hello
Morning
I
Morning
Am
Morning
A
Morning
File
有誰知道如何做到這一點?
抱歉措辭不好,Gomenburu
uj5u.com熱心網友回復:
為避免為大檔案占用主記憶體,您需要隨時插入額外的字串。這并不難,只是有點棘手,以確保它們只在現有行之間,而不是在開頭或結尾:
# 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\n") # Write the in-between "Morning" before each new line
outf.write(line) # Write pre-existing line
uj5u.com熱心網友回復:
with open("words.txt", "r") as words_file, open("newfile.txt", "w") as new_words_file:
new_words_file.write("\n".join([f"{word}\nMorning" for word in words_file.read().split("\n")]))
uj5u.com熱心網友回復:
with open('words.txt') as f:
lines = f.readlines()
for i in range(len(lines)):
a = lines[i] 'Morning' '\n'
with open('newfile.txt','a') as file:
file.write(a)
file.close()
這應該做!
uj5u.com熱心網友回復:
我將從這個開始:
f1 = open( 'words.txt')
f2 = open( 'newfile.txt')
lines = f1.readlines()
for line in lines:
f2.write( line "Morning\n")
f2.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520826.html
