python3打开文件和阅读行

use*_*308 6 python-3.x

你能解释一下这段代码中发生了什么吗?我似乎不明白你如何打开文件并在for循环中逐行读取而不是所有句子.谢谢

假设我在文档文件中有这些句子:

cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3
Run Code Online (Sandbox Code Playgroud)

这是代码:

from sys import argv

filename = input("Please enter the name of a file: ")
f = open(filename,'r')

d1ct = dict()
print("Number of times each animal visited each station:")
print("Animal Id           Station 1           Station 2")

for line in f:
     if '\n' == line[-1]:
          line = line[:-1]
     (AnimalId, Timestamp, StationId,) = line.split(':')
     key = (AnimalId,StationId,)
     if key not in d1ct:
          d1ct[key] = 0
     d1ct[key] += 1
Run Code Online (Sandbox Code Playgroud)

Mos*_*she 8

神奇的是:

for line in f:
     if '\n' == line[-1]:
          line = line[:-1]
Run Code Online (Sandbox Code Playgroud)

Python file对象的特殊之处在于它们可以在for循环中迭代.在每次迭代时,它都会检索文件的下一行.因为它包含行中的最后一个字符(可以是换行符),所以检查和删除最后一个字符通常很有用.


pep*_*epr 7

正如Moshe所写,可以迭代打开的文件对象.只是,它们不是filePython 3.x 中的类型(因为它们在Python 2.x中).如果文件对象在文本模式下打开,则迭代单位是一个文本行,包括\n.

您可以使用line = line.rstrip()删除\n加尾随机空间.

如果要一次读取文件的内容(进入多行字符串),可以使用content = f.read().

代码中有一个小错误.应始终关闭打开的文件.我的意思是f.close()在for循环之后使用.或者你可以将open打开到更新的with构造,它将为你关闭文件 - 我建议你习惯后来的方法.