虽然做了一些Python的教程,这本书的作者提出以下(打开一个文件并读取其内容):打开文件并在一行中阅读内容?
#we could do this in one line, how?
in_file = open(from_file)
indata = in_file.read()
我怎样才能做到这一条线?
虽然做了一些Python的教程,这本书的作者提出以下(打开一个文件并读取其内容):打开文件并在一行中阅读内容?
#we could do this in one line, how?
in_file = open(from_file)
indata = in_file.read()
我怎样才能做到这一条线?
你可以从文件处理程序中获取文件的所有内容,方法是简单地扩展你的路径并从中读取。
indata = open(from_file).read()
但是,如果您使用的是with
块它更明显发生了什么,更容易扩展。
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
除此之外,你应该保护你的文件打开和关闭IOErrors
如果(例如)您的文件路径不存在。
最后,文件默认情况下以只读方式打开,如果您(或其他人以后)尝试写入文件,则会产生错误,这将保护数据块。根据您的需要,您可以将其从'r'
更改为variety of other options。
这是上述概念的一个相当完整的例子。
def get_file_contents(input_path):
try:
with open(input_path, 'r') as fh:
return fh.read().strip()
except IOError:
return None
为什么你想在一行中做到这一点?你想如何获得数据,一个大块'indata = open(from_file).read()'或一列行'indata = list(open(from_file))' – AChampion
任何时候你打开一个文件,你应该可能使用'with'块。看看[这篇文章](http://stackoverflow.com/a/3644618/4541045)关于为什么你要小心打开和关闭文件的一些解释。 – ti7
@AChampion。谢谢你非常有用。我确实需要将数据作为一个大块(如你所建议的)为什么?以便更好地学习编码。谢谢 –