Skip to main content
 首页 » 编程设计

python之读取文件的多种方式

2025年05月04日14daizhj

我不确定在下面第 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)

mode is 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.