markdown 阅读* .txt文件演示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 阅读* .txt文件演示相关的知识,希望对你有一定的参考价值。

# read *.txt file demo

2019年2月19日10:14

```python
# It is a good idea to store the filename into a variable.
# The variable can later become a function argument when the
# code is converted to a function body.
filename = 'data.txt'
# Using the newer with construct to close the file automatically.
with open(filename) as f:
    data = f.readlines()
```
### Or using the older approach and closing the filea explicitly.
```python
# Here the data is re-read again, do not use both ;)
f = open(filename)
data = f.readlines()
f.close()
# The data is of the list type.  The Python list type is actually
# a dynamic array. The lines contain also the \n; hence the .rstrip()
for n, line in enumerate(data, 1):
    print '{:2}.'.format(n), line.rstrip()
print '-----------------'
```
### You can later iterate through the list for other purpose
```python
# for example to read them via the csv.reader.
import csv
reader = csv.reader(data)
for row in reader:
    print row
```
来自 <https://stackoverflow.com/questions/10393176/is-there-a-way-to-read-a-txt-file-and-store-each-line-to-memory> 

以上是关于markdown 阅读* .txt文件演示的主要内容,如果未能解决你的问题,请参考以下文章

一个很小的爬虫,演示了爬一首词,后存进txt文件中去

markdown基础

markdown基础

markdown基础

markdown 同时阅读读取文件

markdown 11. Python - 阅读文件