Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取文件的多种方法?_Python_File - Fatal编程技术网

Python 读取文件的多种方法?

Python 读取文件的多种方法?,python,file,Python,File,我不确定在下面第2行的两种情况下,文件的读取方式是否有差异。第一个场景在open命令中有一个'r',而第二个场景没有。两者都输出相同的结果。这些只是实现相同结果的不同方法吗 情景1: def readit(filename, astr): infile = open(filename, 'r') content = infile.read() infile.close() return content.count(astr) print(readit("payr

我不确定在下面第2行的两种情况下,文件的读取方式是否有差异。第一个场景在open命令中有一个
'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'是
打开的默认模式。从:

open(文件,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)

模式
是一个可选字符串,用于指定打开文件的模式。它默认为
'r'
,这意味着可以在中打开阅读 文本模式


是的,这两个代码段是等效的<代码>'r'
打开的默认模式。从:

open(文件,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)

模式
是一个可选字符串,用于指定打开文件的模式。它默认为
'r'
,这意味着可以在中打开阅读 文本模式

没有区别


没有区别

< p>你可以考虑使用<>代码> 打开文件,除其他好处外,自动关闭文件。最好逐行计算目标字符串,而不是将整个文件读入内存:

def readit(filename, astr):
    with open(filename) as infile:
        return sum(line.count(astr) for line in infile)
更短、更少的内存、更具“Pythonic”


在旁注中,
line.count(astr)
将计算该子字符串的所有出现次数,即使是较大字符串的一部分。例如:

>>> s='she she he she he sheshe hehe'
>>> s.count('she')
5
>>> s.count('he')
9
考虑拆分文本以获得完全匹配:

>>> [word for word in s.split() if word=='she']
['she', 'she', 'she']
>>> [word for word in s.split() if word=='he']
['he', 'he']
或正则表达式:

>>> re.findall(r'\bshe\b', s)
['she', 'she', 'she']
>>> re.findall(r'\bhe\b', s)
['he', 'he']

你可以考虑使用<>代码> < /C> >打开文件,除其他好处外,自动关闭文件。最好逐行计算目标字符串,而不是将整个文件读入内存:

def readit(filename, astr):
    with open(filename) as infile:
        return sum(line.count(astr) for line in infile)
更短、更少的内存、更具“Pythonic”


在旁注中,
line.count(astr)
将计算该子字符串的所有出现次数,即使是较大字符串的一部分。例如:

>>> s='she she he she he sheshe hehe'
>>> s.count('she')
5
>>> s.count('he')
9
考虑拆分文本以获得完全匹配:

>>> [word for word in s.split() if word=='she']
['she', 'she', 'she']
>>> [word for word in s.split() if word=='he']
['he', 'he']
或正则表达式:

>>> re.findall(r'\bshe\b', s)
['she', 'she', 'she']
>>> re.findall(r'\bhe\b', s)
['he', 'he']

从python文档来看,它是相同的。
但是如果您想增加可读性,最好添加python文档中的“r”模式:)

,这是相同的。
但是如果你想增加可读性,最好添加“r”模式:)

谢谢大家!我现在明白了。非常感谢!谢谢大家!我现在明白了。非常感谢!