python - 尝试保存并写入文件

标签 python file python-3.x

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/

相关文章:

python - SpaCy 中的 .pos_ 在 Python 中不返回任何结果

multithreading - 多线程文件访问

python - 如何访问应用程序 'File Description' ?

c++ - C++ 二进制文件如何替换自身?

python - 我可以使用 asyncio 读取和写入 multiprocessing.Pipe 吗?

python - 计算 pandas 中数据框中每一列的值变化,忽略 NaN 变化

python - 用于生成 NumPy 矩阵的矢量化解决方案

python - 网页抓取:访问大列表中的文本信息

python - setup.py 和 py2app 包括 pip 包

python - 如何将这些调用组合到 print()?