我有大的.txt文件列表。为了保存它们,我在做一个for循环,但是问题在于保存的最终文本(不是完整文件)会被剪切掉,因为Python的移动速度太快并且没有时间执行保存所有内容,因为当我尝试在控制台上打印文本时,它位于脚本中,只是不保存。我添加了time.sleep()
,并在3或5秒内将所有内容保存在txt中,但是我想知道一种更好的方法,例如“等到”,以等待保存。因为我不确定要在其他计算机上花费什么时间,或使用不同的.txt文件,所以请提前。
代码:
Text=[Text1, Text2, Text3, Text4]
index=0
for x in List_Of_Names:
Name=str(List_Of_Names[index])
file=open('Texts\\'+Product+'_'+ Name + '.txt', 'w')
file.write(Texts[index])
file.close
time.sleep(5)
index+=1
time.sleep(5)
print('The new .txt files were saved in ' + Location +"\\Scenes" )
print('\n')
print('Press "Enter" to escape.')
wait=sys.stdin.readline()
答案 0 :(得分:2)
看起来您每次迭代都在重写文本内容。
尝试:
with open('Texts\\'+Product+'_'+ Name + '.txt', "w") as infile:
for x in List_Of_Names:
ViewName=str(List_Of_Names[index])
infile.write(Texts[index])
答案 1 :(得分:-1)
使用with
以以下方式打开文件:-
with open('Texts\\'+Product+'_'+ Name + '.txt', 'w') as fd:
fd.write(Texts[index])