简体   繁体   English

通过循环问题保存.txt

[英]Saving a .txt through a loop issue

I have list of big .txt files. 我有大的.txt文件列表。 To save them, I am making a for loop, but the problem is that the final text is cutted when it is saved(it is not the full file), I assume, because Python is moving too fast and don't have time to save everything, because when I try to print the text on the console it is in the script, just not saving. 为了保存它们,我在做一个for循环,但是问题在于保存的最终文本(不是完整文件)会被剪切掉,因为Python的移动速度太快并且没有时间执行保存所有内容,因为当我尝试在控制台上打印文本时,它位于脚本中,只是不保存。 I have added time.sleep() , and with 3 or 5 sec everything is saved in the txt, but I was wondering for better way, something like "wait until", to wait the saving. 我添加了time.sleep() ,并在3或5秒内将所有内容保存在txt中,但是我想知道一种更好的方法,例如“等到”,以等待保存。 Because I am not sure on a different computers what time will take, or with different .txt files.Thanks in advance. 因为我不确定在其他计算机上会花费多少时间,或使用不同的.txt文件,所以请先谢谢。

Code: 码:

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()

Looks like you are re-writing the content of your text with each iteration. 看起来您每次迭代都在重写文本的内容。

Try: 尝试:

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])

Use with for opening the file as:- 用于with以如下方式打开文件:

with open('Texts\\'+Product+'_'+ Name  + '.txt', 'w') as fd:
    fd.write(Texts[index])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM