Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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 - Fatal编程技术网

Python 打开文件并在一行中读取内容?

Python 打开文件并在一行中读取内容?,python,Python,在做一些Python教程时,本书的作者要求提供以下内容(打开一个文件并阅读其内容): 如何在一行中完成此操作?只需扩展路径并从中读取,即可从文件处理程序获取文件的所有内容 indata = open(from_file).read() 但是,如果将与块一起使用,发生的事情会更明显,扩展起来也更容易 with open(from_file) as fh: # start a file handler that will close itself! indata = fh.read()

在做一些Python教程时,本书的作者要求提供以下内容(打开一个文件并阅读其内容):


如何在一行中完成此操作?

只需扩展路径并从中读取,即可从文件处理程序获取文件的所有内容

indata = open(from_file).read()
但是,如果将
块一起使用,发生的事情会更明显,扩展起来也更容易

with open(from_file) as fh:  # start a file handler that will close itself!
    indata = fh.read()  # get all of the contents of in_file in one go as a string
除此之外,如果(例如)文件路径不存在,则应保护文件的打开和关闭

最后,默认情况下,文件是以只读方式打开的,如果您(或稍后的其他人)尝试写入文件,则会引发错误,这将保护数据块。根据您的需要,您可以将其从
'r'
更改为a

下面是一个包含上述概念的相当完整的示例

def get_file_contents(input_path):
    try:
        with open(input_path, 'r') as fh:
            return fh.read().strip()
    except IOError:
        return None

你为什么要在一行中完成它?你想要怎样的数据,一个大的块
indata=open(从_文件).read()
或一个行列表
indata=list(open(从_文件))
任何时候你打开一个文件,你可能都应该使用
块。请看一些关于为什么要小心打开和关闭文件的解释。@AChampion。谢谢你,非常有用。我确实需要数据作为一个大块(正如你所建议的)为什么?很好地学习一种更简洁的编码方法。谢谢,一行不一定要整洁-惯用的方法是打开(从文件中)的
,如在文件中:indata=in\u file.read()
read-up about
indata=None
没有帮助,
indata
将有一个值,或者将引发一个异常-如果您可以优雅地处理它,则捕获异常,并在那里为
indata
指定一个默认值。您是正确的-关于try/异常的半书面想法可能会令人困惑-我将删除它并创建一个完整的示例。默认模式为
r
,因此,如果有人尝试使用或不使用显式模式arg对其进行写入,则会发生错误。
def get_file_contents(input_path):
    try:
        with open(input_path, 'r') as fh:
            return fh.read().strip()
    except IOError:
        return None