Skip to main content
 首页 » 编程设计

python之尝试保存并写入文件

2025年05月04日7kevingrace

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)