python删除txt文件第三行_每第一行、第二行和第三行读取一个txt文件,并保存在3个不同的列表中...

我认为,你思维中的一个基本缺陷是,你想读所有的第一行数字,然后读第二行。最好一次通读该文件,而不是在阅读文件时对不同的行进行排序。一种方法是在另一个答案中使用行计数器mod 3,或者您可以继续在for循环中读取行,如下所示:myFileList= """first line

2nd line

3rd line

#Mi Mj

#Ni Nj Nk

#Pi Pj

#----------- The numeric values start here ------

M0 M1

N0 N1 N2

P0 P1

M1 M2

N1 N2 N3

P1 P2

M2 M3

N2 N2 N3

P2 P3"""

myFakeFile = iter(myFileList.split('\n'))

m,n,p = [], [], []

m2, n2, p2 = [], [], []

# Skip the first few lines

for skip_lines in range(7):

next(myFakeFile)

# Read the next line ...

for line in myFakeFile:

# ... and the following two lines

second_line = next(myFakeFile)

third_line = next(myFakeFile)

# Either append line directly,

m.append(line)

n.append(second_line)

p.append(third_line)

# or split the lines before appending

m2.extend(line.split())

n2.extend(second_line.split())

p2.extend(third_line.split())

print('m = {}'.format(m))

print('n = {}'.format(n))

print('p = {}\n'.format(p))

print('m2 = {}'.format(m2))

print('n2 = {}'.format(n2))

print('p2 = {}\n'.format(p2))

我有点不确定您是否希望下次拆分实际的行,因此我添加了m2, n2, p2列表来显示这一点。我必须伪造文件才能得到一个运行的例子。但此代码生成以下输出:

^{pr2}$

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值