Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 一旦提供了有效的文件名,如何退出for循环,并为正确输入提供3次机会_Python - Fatal编程技术网

Python 一旦提供了有效的文件名,如何退出for循环,并为正确输入提供3次机会

Python 一旦提供了有效的文件名,如何退出for循环,并为正确输入提供3次机会,python,Python,我试图写一个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 e

我试图写一个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-and-except语句来实现这一点。谢谢大家!


干杯

操作系统模块

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

演示:

中断关键字

使用
break
关键字从任意迭代器循环中出来,即
for
while

演示


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

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

注意:

对Python2.x使用
raw\u input()

对Python3.x使用
input()

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