python读取txt文件每一行存为列表_python – 有没有办法读取.txt文件并将每一行存储到内存?...

我知道它已经回答了:)总结一下上面的内容:

# 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.

# 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, for

# example to read them via the csv.reader.

import csv

reader = csv.reader(data)

for row in reader:

print row

它在我的控制台上打印:

1. 12,12,12

2. 12,31,12

3. 1,5,3

-----------------

['12', '12', '12']

['12', '31', '12']

['1', '5', '3']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值