我在python中创建了一个文本文件,我正在努力研究如何从python中的文本文件打印某些行。希望可以有人帮帮我。我知道它与f.write或f.read有关。从python中读取和写入文件
-5
A
回答
0
你可以尝试这样的事:
f = open("C:/file.txt", "r") #name of file open in read mode
lines = f.readlines() #split file into lines
print(lines[1]) #print line 2 from file
+0
谢谢,这真的有帮助 – H14
0
with open('data.txt') as file_data:
text = file_data.read()
如果您正在使用*上传.json文件很好的解决方案是:
data = json.loads(open('data.json').read()))
0
使用with
关键词来自动处理文件后闭幕打开文件。
with open("file.txt", "r") as f:
for line in f.readlines():
print line #you can do whatever you want with the line here
即使您的程序在执行期间中断,它也会处理文件关闭。另一种 - 做同样的手动方式是:
f = open("file.txt", "r")
for line in f:
print line
f.close()
但要小心,只有在你的循环执行后才会关闭。也可以看到这个答案Link
相关问题
- 1. 从python中读取/写入android文件
- 2. 从plist文件中写入和读取
- 3. 写入和从文件中读取
- 4. Python文件读取+写入
- 5. Python快速读取和写入文件
- 6. Python:读取和写入CSV文件
- 7. Python:读取和写入多个文件
- 8. 同时读取和写入python文件
- 9. 在Python中写入文件,使用Arduino从文件中读取
- 10. 从csv文件读取和写入
- 11. 从文件读取和写入
- 12. Android - 从文件读取和写入
- 13. 读取和写入文件
- 14. 写入和读取文件
- 15. 在Python中读取/写入文件
- 16. 使用Python和Javascript从Json文件读取和写入
- 17. python从文件中读取写入其他文件
- 18. 使用Python从MS Azure读取和写入文件
- 19. NSDocumentDirectory - 写入并从文件中读取
- 20. 在Haskell中读取和写入文件
- 21. 在C++中读取和写入文件
- 22. 在iPhone中读取和写入文件
- 23. 从.txt文件中读取和写入.txt文件
- 24. python读取/写入文件列表
- 25. 在Python中的文件中读取和写入数组
- 26. Python文件读取二进制文件和写入xml
- 27. 读取和写入文本文件
- 28. 如何在python中写入和读取文件?
- 29. 如何在Python中读取/写入xlsx和xls文件?
- 30. 如何在Python中读取和写入CSV文件
可能重复[Python:逐行读入文件到数组中](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array ) – 2016-02-19 13:19:16
您可能错过了本教程中有关[读写文件](https://docs.python.org/3.5/tutorial/inputoutput.html#reading-and-writing-files)的部分。 – Matthias