如何限制python中文件名的检查?

如何限制python中文件名的检查?,python,Python,我正在尝试编写一个程序,要求输入一个特定的文件名,然后处理输入的文件名,从中列出一个列表。限制是用户只有三次机会键入正确的文件名。这是我的密码: import os.path def file_name_tries(): for i in range(3): filename = input('please enter filename: ') try: infile = open(filename,'r') # Do w

我正在尝试编写一个程序,要求输入一个特定的文件名,然后处理输入的文件名,从中列出一个列表。限制是用户只有三次机会键入正确的文件名。这是我的密码:

    import os.path

def file_name_tries():
    for i in range(3):
        filename = input('please enter filename: ')
    try:
        infile = open(filename,'r')
        # Do whatever you want, e.g.
        #print infile.read()
        return infile
        exit()
    except IOError:
        if not os.path.exists(filename): print ('File does not exist')
        else: print ('Error opening file')

    print ('you have exceed your three tries' )   
def process_file():
    #file_name=input('file name: ')
    #input_file=open(file_name,'r')
    input_file=file_name_tries()
    input_list=[]
    #for loop strips each line of end characters
    #and splits each line of the input file at ; and turns the line to a list
    for line in input_file:
        line_list=line.strip().split(';')
        #appends each line_list to input_list
        input_list.append(line_list)
    print( input_list)
process_file()
错误:

please enter filename: mlb.txt
please enter filename: mlb.txt
please enter filename: mlb.txt
File does not exist
you have exceed your three tries
Traceback (most recent call last):
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project   07\passwordenter3times.py", line 29, in <module>
    open_file()
  File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 24, in open_file
    for line in input_file:
TypeError: 'NoneType' object is not iterable

请输入文件名:mlb.txt

请输入文件名:mlb.txt
请输入文件名:mlb.txt 文件不存在 你已经超过了你的三次尝试 回溯(最近一次呼叫最后一次): 文件“C:\Users\Dasinator\Documents\Books IX\Python Examples\textube Examples\project 07\passwordenter3times.py”,第29行,在 打开_文件() 文件“C:\Users\Dasinator\Documents\Books IX\Python Examples\textube Examples\project 07\passwordenter3times.py”,第24行,在open\u文件中 对于输入_文件中的行: TypeError:“非类型”对象不可编辑

如有任何建议,我将不胜感激。谢谢

当用户成功打开
返回文件时,只需更换您的
中断
(并删除底部的返回,这会导致错误)


如果用户失败三次,则函数将返回None。

将其另存为
test.py

import os
for i in range(3):
    filename = raw_input('please enter filename: ')
    try:
        infile = open(filename,'r')
        # Do whatever you want, e.g.
        print infile.read()
        exit()
    except IOError:
        if not os.path.exists(filename): print 'File does not exist'
        else: print 'Error opening file'

print 'you have exceed your three tries'
以下是它在终端上的工作原理:

$ rm test.txt
$ python test.py
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
you have exceed your three tries
$ echo "this is a foo bar" > test.txt
$ python test.py
please enter filename: test.txt
this is a foo bar
$ rm test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist

you have exceed your three tries
program ending... byebye...
$ echo 'foo bar sentence, blah blah' > test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt

reading file...
foo bar sentence, blah blah

要“功能化”最多三次尝试打开文件,请尝试:

import os

def three_tries():
    for i in range(3):
        filename = raw_input('please enter filename: ')
        try:
            infile = open(filename,'r')
            return infile
        except IOError:
            if not os.path.exists(filename): print 'File does not exist'
            else: print 'Error opening file'
    print '\nyou have exceed your three tries'
    print 'program ending... byebye...'
    exit()

print 'this is a foo bar script'
print 'i am going to ask the user for a filename'
infile = three_tries()
# Do whatever you want with the file, e.g.
print '\nreading file...'
print infile.read()
在终端上:

$ rm test.txt
$ python test.py
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
you have exceed your three tries
$ echo "this is a foo bar" > test.txt
$ python test.py
please enter filename: test.txt
this is a foo bar
$ rm test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist
please enter filename: test.txt
File does not exist

you have exceed your three tries
program ending... byebye...
$ echo 'foo bar sentence, blah blah' > test.txt
$ python test.py
this is a foo bar script
i am going to ask the user for a filename
please enter filename: test.txt

reading file...
foo bar sentence, blah blah
如果您不希望程序在超过三次尝试后结束:

import os

def three_tries():
    for i in range(3):
        filename = raw_input('please enter filename: ')
        try:
            infile = open(filename,'r')
            return infile
        except IOError:
            if not os.path.exists(filename): print 'File does not exist'
            else: print 'Error opening file'
    print '\nyou have exceed your three tries'
    print 'continuing without reading any file...'
    return

print 'this is a foo bar script'
print 'i am going to ask the user for a filename'
infile = three_tries()

if infile:
    # Do whatever you want with the file, e.g.
    print '\nreading file...'
    print infile.read()
else:
    print 'no file read, continuing to other stuff...'

print 'now you can continues to other parts of the program...'

我试过了,但仍然不起作用。它甚至不允许我三次输入错误的文件名。您是否注意到,您的“for”循环提供了3次尝试,但实际上不包括
input()
函数调用?因此,用户当然只能得到一次提示。你的编码要更有条理,它应该会工作得更好。我对你的代码做了一些编辑并运行了代码,我得到了我在主代码中发布的新错误消息。请看一看。只要扔掉打开的文件(),代码就可以了。为什么需要打开_文件()
file\u name\u tries()
不返回任何内容,因此open\u file()中存在非类型错误。是否要记录用户的条目?或者你想做些别的事情。您需要澄清
open_file()
的用途,以便我们帮助您=)。我已将函数名更改为process_file,因为它正在调用open_file函数并处理打开的文件并创建列表。我希望这是有意义的。请查看其他答案并检查这是否是您所需要的。呃,为什么您甚至需要
open_file()
?只需调用
file\u name\u tries()
。我有点困惑。是否要以交互方式检查文件是否存在?或者要求用户输入3个文件并检查存在哪些文件?您需要为我们澄清任务,以便更好地帮助您。=)这是一个更大计划的一部分。抱歉,试图给出部分程序而不是整个代码(太长了)。第一个功能是打开文件,第二个功能是处理打开的文件并创建列表。谢谢。它正在工作。但是,我想知道我们是否可以用其他东西替换exit()。在三次试验失败的情况下,我希望输出窗口保持打开状态。这完全取决于较大的程序如何交互,以及您希望程序如何、何时何地结束。但是你已经有了如何限制文件打开尝试的想法;P.您可以使用return而不是exit(),但是在继续代码的其他部分之前,您必须检查
infle是否为None
。所以所有的贝斯!在编辑的版本中,它返回none,none不可编辑。因此,使用此函数处理打开的文件并创建列表的函数出现错误。无论如何,谢谢你解决我的问题。我将看到如何修改它,使其与其他功能一起工作。请输入文件名:mlb.txt文件不存在请输入文件名:mlb.txt文件不存在请输入文件名:mlb.txt文件不存在您已超过三次尝试回溯(最近一次调用):文件“C:\Users\Dasinator\Documents\Books IX\Python Examples\textcool Examples\project 07\passwordenter3times.py”,第34行,在open\u file()文件“C:\Users\Dasinator\Documents\Books IX\Python Examples\textcool Examples\project 07\passwordenter3times.py”中,第29行,在输入文件中的第行的打开文件中:TypeError:“NoneType”对象不是iterableThanks谢谢您的帮助。我终于学会了如何在我的程序中使用你的代码,非常感谢你的帮助。