Python:如何在python中输入文件名

时间:2012-03-10 09:07:45

标签: python

我对python很新。 当我做fileofname = "a2.txt" 那么我可以毫无问题地运行我的代码 但是,当我fileofname = raw_input("enter the file name:")时 然后我键入“a2.txt” 它引发了"UnboundLocalError: local variable 'line' referenced before assignment"

有人能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

fileofname = raw_input("enter the file name:")
fileObject = open(fileofname, 'r')
for line in fileObject:
    print line

答案 1 :(得分:0)

我假设您需要阅读CSV文件

import csv
import os

ifilename = raw_input('Enter a file name: ')
ifile  = open(ifilename, "rb")
reader = csv.reader(ifile)
for row in reader:
     .......
     .........
     ..........

如果您需要阅读txt文件:

import os

print "Enter a file name:",
filename = raw_input()

OR

filename = raw_input('Enter a file name: ')