Creating file loop

左心房为你撑大大i 提交于 2020-01-07 02:01:20

问题


How can I ask the user for a file name and if it already exists, ask the user if they want to overwrite it or not, and obey their request. If the file does not exist, a new file (with the selected name) should be created. From some research on both the Python website and Stack Overflow, I've come up with this code

try:
    with open(input("Please enter a suitable file name")) as file:
        print("This filename already exists")

except IOError:
    my_file = open("output.txt", "r+")

But this will not run in Python, and doesn't do everything I want it to do.


回答1:


Alternative soltution would be (however the user would need to provide a full path):

import os

def func():
    if os.path.exists(input("Enter name: ")):
        if input("File already exists. Overwrite it? (y/n) ")[0] == 'y':
            my_file = open("filename.txt", 'w+')
        else:
            func()

    else:
    my_file = open("filename.txt", 'w+')

Don't forget to close the file object when it's not needed anymore with my_file.close().




回答2:


You can use os.path.exists to check if a file already exists are not.

if os.path.exists(file path):
    q = input("Do you want to overwrite the existing file? ")
    if q == (your accepted answer):
       #stuff
else:
    #stuff

You could do this with a try / except if you want to abide by the whole "easier to ask for forgiveness" motto, but I think this is cleaner.



来源:https://stackoverflow.com/questions/38294000/creating-file-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!