我不确定在下面第 2 行的两种情况下读取文件的方式是否存在差异。第一种情况在打开命令中有一个 'r',并且第二个没有。两者输出相同的结果。这些只是实现相同结果的不同方法吗?
场景 1:
def readit(filename, astr):
infile = open(filename, 'r')
content = infile.read()
infile.close()
return content.count(astr)
print(readit("payroll.txt","Sue"))
场景 2:
def readit(filename, astr):
infile = open(filename)
content = infile.read()
infile.close()
return content.count(astr)
print(readit("payroll.txt","Sue"))
请您参考如下方法:
是的,这两段代码是等价的。 'r' 是打开 的默认模式。来自docs :
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
modeis an optional string that specifies the mode in which the file is opened. It defaults to'r'which means open for reading in text mode.
