我想将整个文件读入python列表任何一个知道如何?如何将整个文件读入python列表中?
4
A
回答
3
print "\nReading the entire file into a list."
text_file = open("read_it.txt", "r")
lines = text_file.readlines()
print lines
print len(lines)
for line in lines:
print line
text_file.close()
+1
其实在这里不需要迭代两次 - 第一次使用readlines,第二次使用for循环 –
0
或者:
allRows = [] # in case you need to store it
with open(filename, 'r') as f:
for row in f:
# do something with row
# And/Or
allRows.append(row)
请注意,您不需要在这里关心关闭文件,也没有必要在这里使用readlines方法。
5
简单:
with open(path) as f:
myList = list(f)
如果你不想换行,你可以做list(f.read().splitlines())
1
Max的回答会的工作,但你会留下在endline
字符(\n
)每一行的结尾。
除非这是期望的行为,请使用以下模式:
with open(filepath) as f:
lines = f.read().splitlines()
for line in lines:
print line # Won't have '\n' at the end
相关问题
- 1. 将txt文件读入列表Python
- 2. 将.csv文件读入Python列表
- 3. 将文件读入列表?
- 4. 如何用Python 2.7将整数列表写入文件?
- 5. 如何将文本文件中的数字读入python列表中的数字?
- 6. 将文件列表读入DataFrame列表
- 7. 如何将列表列表写入cgi/python中的文件?
- 8. 如何在python中将列表列表写入文件?
- 9. 从文本文件读入python列表
- 10. python将一个列表写入文件
- 11. 如何在Python中将文件列表写入文件?
- 12. 如何将json文件读入python?
- 13. 如何将c中的整个文件读入数组数组
- 14. 如何在JAVA中将文本文件读入数组列表?
- 15. Python如何从文件中读取和写入列表
- 16. 如何在Python中将文本列表写入文本文件
- 17. Python从文件列表中列入整数列表
- 18. 将整个文件读入数组
- 19. python读取/写入文件列表
- 20. Python - 从文件读入列表
- 21. 将文件txt读入列表2 Python中的维度
- 22. 读取.csv文件并将其内容放入python列表中
- 23. 将列表写入python中的文件?
- 24. 如何将列表的列表写入CSV文件Python?
- 25. 试图将文件中的信息读入Python中的两个列表中
- 26. 将整数放入python列表中
- 27. 如何在java中将.csv文件读入数组列表?
- 28. 如何将文件中的浮点数读入列表
- 29. 将.db文件读入Python
- 30. 如何从文件中读取并将其作为整数放入列表中? Python的
您正在使用什么教程学习Python? –
你有没有读过Python文档的_any_? –