笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册
查看: 5243|回复: 1

[已经解决] TXT数据处理

[复制链接]

新手上路

Rank: 1

积分
3
发表于 2022-3-10 08:11:21 | 显示全部楼层 |阅读模式
最近在编写个小程序,想要对比两个文件内数据值,再替换文件的第一列,然后存储于TXT文件内,程序如下
  1. result1=[]
  2. with open('text1.txt','r') as f:
  3.         for line in f:
  4.                 result1.append(list(line.strip('\n').split(',')))
  5. #可打印出对应列表的数字print(result[5][2])
  6. #print (result1)
  7. f.close()
  8. result2=[]
  9. with open('text2.txt','r') as f:
  10.         for line in f:
  11.                 result2.append(list(line.strip('\n').split(',')))
  12. #print(result2)
  13. f.close()
  14. for temp1 in result1:
  15.         for temp2 in result2:
  16.                 if temp2[1:6] == temp1[1:6]:
  17.                       temp1[0]=temp2[0]
  18.                       print(temp2)
  19.                       f=open('结果.txt','w')
  20.                       f.write(str(temp2))
  21.                       f.close()
复制代码
但是保存的'结果文档内只有‘temp2'列表的最后一行,  请问是怎么回事
['15', '5272', '5376', '5377', '5378', '15000', '14999', '14998', '15002', '15001', '15003']
['6', '5272', '5376', '5378', '5379', '15000', '15001', '15002', '15005', '15004', '15006']
['17', '5272', '5383', '5378', '5384', '15025', '15024', '15002', '15027', '15026', '15028']
['8', '5402', '5383', '5378', '5364', '15080', '15024', '15079', '15082', '15081', '15083']
['1', '5402', '5377', '5404', '5378', '15092', '15091', '15090', '15079', '15003', '15093']
['20', '5405', '5406', '5407', '5408', '15096', '15095', '15094', '15098', '15097', '15099']
['1', '5405', '5409', '5410', '5411', '15102', '15101', '15100', '15104', '15103', '15105']
['2', '5405', '5408', '5417', '5415', '15098', '15123', '15122', '15117', '15124', '15125']
['2', '5405', '5417', '5416', '5415', '15122', '15126', '15120', '15117', '15125', '15121']
['98', '5262', '5273', '5272', '5271', '14736', '15016', '14730', '14732', '14735', '14731']这是'temp2;
结果内只有最后一行
青菜白玉汤咯已获得悬赏 10 C币

最佳答案

追加模式写'a'不是'w' 内容字符串+'\n'
回复

使用道具 举报

新手上路

Rank: 1

积分
2
发表于 2022-3-10 08:11:40 | 显示全部楼层
追加模式写'a'不是'w'
内容字符串+'\n'
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 09:42 , Processed in 0.045343 second(s), 24 queries .

© 2001-2020

快速回复 返回顶部 返回列表