python读取文件到字符串中
时间:2020-02-23 14:43:13 来源:igfitidea点击:
在本教程中,我们将看到如何将文件读取到字符串变量中。
有多种方法可以在Python中读取文件。
使用read()方法
以下是将文件读取到Python中的字符串的步骤。
- 使用读取模式打开文件
open()方法并将其存储在变量中名为file - 称呼
read()函数file变量并将其存储到字符串变量中countriesStr。 - 打印
countriesStr多变的
让我们首先看到内容 countries.txt我们要读的文件。
$ cat countries.txt #Country,Capital India,Delhi China,Shangai England,London France,Paris
python代码将文件读入字符串
with open('countries.txt','r') as file:
countriesStr = file.read()
print(countriesStr)
使用pathlib.
你也可以使用 pathlib模块将文本文件内容复制到字符串变量并以一行关闭文件。
请注意 pathlib库 可用 Python 3.5 or later。
from pathlib import Path
countriesStr=Path('countries.txt').read_text()
print(countriesStr)
输出:
#Country,Capital Netherlands,Delhi China,Shangai Bhutan,Thimpu France,Paris

