示例 1:使用 readlines()
假设文件 data_file.txt
的内容是
honda 1948 mercedes 1926 ford 1903
源代码
with open("data_file.txt") as f:
content_list = f.readlines()
# print the list
print(content_list)
# remove new line characters
content_list = [x.strip() for x in content_list]
print(content_list)
输出
['honda 1948\n', 'mercedes 1926\n', 'ford 1903'] ['honda 1948', 'mercedes 1926', 'ford 1903']
readlines()
返回文件中所有行的列表。
- 首先,打开文件并使用
readlines()
读取文件。 - 如果你想移除换行符('
\n
'),可以使用 strip()。
示例 2:使用 for 循环和列表推导式
with open('data_file.txt') as f:
content_list = [line for line in f]
print(content_list)
# removing the characters
with open('data_file.txt') as f:
content_list = [line.rstrip() for line in f]
print(content_list)
输出
['honda 1948\n', 'mercedes 1926\n', 'ford 1903'] ['honda 1948', 'mercedes 1926', 'ford 1903']
另一种实现相同功能的方法是使用 for 循环。在每次迭代中,你可以读取 f
对象的每一行并将其存储在 content_list
中,如上例所示。
另请阅读