尝试保存并写入文件

时间:2016-03-11 08:20:22

标签: 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
>>>

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

2 个答案:

答案 0 :(得分:1)

在您尝试"的代码部分中。要打开文件,文件还没有存在,所以它会进入"除了"部分(休息),程序终止。

     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 

将其替换为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)

答案 1 :(得分:0)

当您打开文件时,您需要创建一个变量来保存该文件并写入该文件。

现在,您尝试在字符串上调用writelines,而不是文件:confirm2.writelines(new_glider)

以下是如何正确写入文件:

with open(confirm, 'w') as f:
    f.writelines(new_glider)