我一直试图让这段代码工作一段时间,而对于我的生活,我找不到问题。尝试打开并读取文本文件时,出现“无此文件或目录”错误。该文件在我的桌面上,所以我知道我没有使用错误的名称。
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Please Enter File Name: ')
# Open the specified file for reading
file = open(fileName, 'r')
# Priming read
line = file.readline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rstrip('\n')
print(line)
line = file.readline()
# Update counter when line is read
counter +=1
# Close file
file.close()
# Call the main function.
main()
答案 0 :(得分:1)
您可能需要指定文件的完整路径。
def main():
# Declare variables
line = ''
counter = 0
# Prompt for file name
fileName = input('Please Enter File Name: ')
# Open the specified file for reading
file_path = path.join(r'C:\Users\jblow\Desktop', fileName)
file = open(fileName, 'r')
# Priming read
line = file.readline()
counter = 1
# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '\n'
line = line.rstrip('\n')
print(line)
line = file.readline()
# Update counter when line is read
counter +=1
# Close file
file.close()
# Call the main function.
main()
答案 1 :(得分:0)
你打算
吗?def main():
...
和
main()
在不同的缩进级别?或者这只是输入问题时的格式问题?我知道这可能不是答案,但是不时会让我感到沮丧......:)