为什么在Python上运行该程序时无法识别文件名?

时间:2018-11-29 12:53:13

标签: python

def file_naming():
    """The users input defines the name of the file"""
    filename=input("Name your file: ") #user's input is set as the file name
    return filename #returns filename so it can be used later in the program

def naming(filename):
    """Taking the users input to put text in to the text file"""
    print("opening file{}",format(filename))
    finished=True
    with open(filename,'w')as f:
        while not finished:
            line=input("please input word(s), empyty to quit: ")
            if line !="":
                f.write(line+'\n')
            else:
                finished=True
def main():
    filename=file_naming()
    naming(filename)

if __name__=='__main__':
    main()

def length():
    """Output the longest sentence from the user's input""" 
    maxlength=0
    infile=open("30075165.txt","r")
    for line in infile:
        linelength=lengthofline
        if linelength>maxlength:
            maxlength=linelength
            linelength=line
print maxlinetext
infile.close()

1 个答案:

答案 0 :(得分:0)

您的代码存在一些问题:长度函数中的缩进,输入应为“ raw_input”(假设您使用的是Python2.x。在Python 2.x input中,它不被视为字符串,raw_input是),而while循环不起作用。

除此之外,length函数不会被调用,并且会打开一个静态文件(而不是您的用户输入?)。我做到了这一点。

def file_naming():
    """The users input defines the name of the file"""
    filename = raw_input("Name your file: ") #user's input is set as the file name
    return filename #returns filename so it can be used later in the program

def naming(filename):
    """Taking the users input to put text in to the text file"""
    print("opening file{}",format(filename))
    not_finished = True
    with open(filename,'w') as f:
        while not_finished:
            line = raw_input("please input word(s), empyty to quit: ")
            if line != "":
                f.write(line+'\n')
            else:
                not_finished = False

def length(filename):
    """Output the longest sentence from the user's input""" 
    maxlength = 0
    with open(filename,"r") as infile:
        for line in infile:
            linelength = len(line)
            if linelength > maxlength:
                maxlength = linelength
                maxlinetext = line
        print(maxlinetext)
        infile.close()

def main():
    filename = file_naming()
    naming(filename)
    length(filename)

if __name__=='__main__':
    main()