如何阅读整行?
How to read the whole line?
我尝试向用户询问行号并显示它,但它一直显示第一个字母而不是行。
而且我不知道如何循环 IoError 和 IndexError。
谢谢
这是我的代码
def file_content(file_name):
user_file = open(file_name, 'r')
content = user_file.read()
user_file.close()
return content
def main():
file_name = input('Enter the name of the file: ')
try:
content = file_content(file_name)
except IOError:
print ('File can not be fount. Program wil exit.')
exit()
try:
line_number = int(input('Enter a line number: '))
except ValueError:
print ('You need to enter an integer for the line number. Try again.')
except IndexError:
print ('that is not a valid line number. Try again.')
print ('The line you requested:')
print (content[line_number-1])
main()
content
只是您使用的文件内容 read()
- 所以打印 content[-1]
会打印内容中的最后一件事,即最后一个字符。
如果您希望内容是行,a) 打开文件“rt”和 b) 使用 readlines()
读取它,您可能需要注意包括以行结尾的行:
def file_content(file_name):
user_file = open(file_name, 'rt')
content = user_file.readlines()
user_file.close()
return content
现在 content[-1]
是最后一行。
巴尼有一个很好的答案,但是 using readlines() isn't a best practice。您可能会考虑将 file_content
函数替换为不会立即将整个文件加载到内存中的函数,如下所示:
def file_content(filename):
result = []
with open(filename, 'r') as input_file:
result = list(input_file)
return result
我尝试向用户询问行号并显示它,但它一直显示第一个字母而不是行。
而且我不知道如何循环 IoError 和 IndexError。
谢谢
这是我的代码
def file_content(file_name):
user_file = open(file_name, 'r')
content = user_file.read()
user_file.close()
return content
def main():
file_name = input('Enter the name of the file: ')
try:
content = file_content(file_name)
except IOError:
print ('File can not be fount. Program wil exit.')
exit()
try:
line_number = int(input('Enter a line number: '))
except ValueError:
print ('You need to enter an integer for the line number. Try again.')
except IndexError:
print ('that is not a valid line number. Try again.')
print ('The line you requested:')
print (content[line_number-1])
main()
content
只是您使用的文件内容 read()
- 所以打印 content[-1]
会打印内容中的最后一件事,即最后一个字符。
如果您希望内容是行,a) 打开文件“rt”和 b) 使用 readlines()
读取它,您可能需要注意包括以行结尾的行:
def file_content(file_name):
user_file = open(file_name, 'rt')
content = user_file.readlines()
user_file.close()
return content
现在 content[-1]
是最后一行。
巴尼有一个很好的答案,但是 using readlines() isn't a best practice。您可能会考虑将 file_content
函数替换为不会立即将整个文件加载到内存中的函数,如下所示:
def file_content(filename):
result = []
with open(filename, 'r') as input_file:
result = list(input_file)
return result