gpt4 book ai didi

python - 尝试保存并写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 05:34:55 25 4
gpt4 key购买 nike

while True: # Saving a file in txt file
print("Would you like to save the latest generation? ('y' to save): ")
saveInput = input()
if saveInput == 'y' or saveInput == 'Y':
print("Enter destination file name: ")
fileName = input()

try:
open(fileName, "r")
close(fileName)
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()

if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')

elif confirm == 'y':
open(confirm, 'w')
for line in new_glider:
confirm2.writelines(new_glider)

print(new_glider)



except:
break

这是我到目前为止得到的,我试图首先读取一个文件,从中获取数据,然后通过我的程序运行它,最后询问他们是否要保存它,如果文件存在则询问是否他们想覆盖它,如果不创建一个新的,但是当我尝试输入目的地名称后它会跳过,如下所示:

输出

Enter input file name: 
g.txt

How many new generations would you like to print?
4
Would you like to save the latest generation? ('y' to save):
y
Enter destination file name:
g.txt
>>>

有人能帮帮我吗?我已经坚持了一段时间

最佳答案

在您“尝试”打开文件的代码部分,文件尚不存在,因此它到达“except”部分(break),程序终止。

     try:            open(fileName, "r")            close(fileName)            print("Do you want to overwrite that file? ('y' to continue): ")            confirm = input()            if confirm == 'n':                print("Enter destination file name: ")                confirm2 = input()                open(confirm2, 'w')            elif confirm == 'y':                open(confirm, 'w')                for line in new_glider:                    confirm2.writelines(new_glider)                print(new_glider)        except:               break 

Replace it with os.path.isfile(fileName)

if os.path.isfile(fileName):
print("Do you want to overwrite that file? ('y' to continue): ")
confirm = input()

if confirm == 'n':
print("Enter destination file name: ")
confirm2 = input()
open(confirm2, 'w')

elif confirm == 'y':
open(**fileName**, 'w')

for line in new_glider:
confirm2.writelines(new_glider)

print(new_glider)

# if fileName doesn't exist, create a new file and write the line to it.
else:
open(**fileName**, 'w')

for line in new_glider:
confirm2.writelines(new_glider)

print(new_glider)

关于python - 尝试保存并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35935325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com