gpt4 book ai didi

python - 如何在提供有效文件名后退出 for 循环并给出 3 次正确输入的机会

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

我正在尝试编写一个 for 循环,让用户 3 次尝试提供正确的文件名。执行此操作的最佳方法或最佳实践是什么?

for n in [1,2,3]:
try:
user_inp = input('Please provide the filename: ') # Prompt user for file name
# Need help here..
# If the filename isn't found, python will give the following error: FileNotFoundError: [Errno 2] No such file or directory:
# If that happens, I need it to print the except statement and try again
# However, if the filename is correct or "FileIsFound" I need it to exit the loop--using ' break ' ?
except:
print('Invalid file name, try again please')
# Would be great if we could add a counter here like: print('You have', n, 'tries remaining')
continue

file_open = open(user_inp) # open file --load in memory

for line in file_open: # remove /n at the end of each line
line = line.rstrip() # print statements add /n = newlines and text docs usually have /n in them
# this for loop will remove/strip the /n at the end of each line

read_file = file_open.read() # reads entire file
# NOTE: if you are dealing with large files, you may want to consider using a conditional statement to find what you are searching, extracting, etc instead of reading the entire file


print(read_file.upper()) # Prints file contents in upper case

我想知道如何使用 try 和 except 语句来执行此操作。谢谢!

干杯。

最佳答案

操作系统模块

使用 os 模块中的 isfile() 方法检查文件是否存在。

演示:

>>> import os
>>> os.path.isfile("/1.txt")
False
>>> os.path.isfile("/home/vivek/Desktop/file3.csv")
True
>>>

中断关键字

使用 break 关键字从任何迭代器循环中退出,即 forwhile

演示

>>> c = 1
>>> while True:
... if c==3:
... print "Now break because value of c (%d) is equal to 3"%(c)
... break
... print "In loop c=%d"%c
... c += 1
...
In loop c=1
In loop c=2
Now break because value of c (3) is equal to 3
>>>
<小时/>

从用户获取文件名并验证文件名的代码。

import os

file_path = ""
for n in [1,2,3]:
user_inp = raw_input('Please provide the filename: ')
if os.path.isfile(user_inp):
file_path = user_inp
break
print('Invalid file name, try again please')


if file_path:
# Write ypur code.
print "Processing file Name:", file_path
else:
print "User not enters correct file name."

输出:

$ python test1.py
Please provide the filename: /home/Desktop/1.txt
Invalid file name, try again please
Please provide the filename: /home/Desktop/2.txt
Invalid file name, try again please
Please provide the filename: /home/Desktop/3.txt
Invalid file name, try again please
User not enters correct file name.

$ python test1.py
Please provide the filename: /home/Desktop/2.txt
Invalid file name, try again please
Please provide the filename: /home/vivek/Desktop/file3.csv
Processing file Name: /home/vivek/Desktop/file3.csv
<小时/>

注意:

对 Python 2.x 使用 raw_input()

对 Python 3.x 使用 input()

关于python - 如何在提供有效文件名后退出 for 循环并给出 3 次正确输入的机会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236123/

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