从文件中读取并写入到另一个python [英] Read from file and write to another python
本文介绍了从文件中读取并写入到另一个python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文件,内容如下
to-56 Olive 850.00 10 10
to-78 Sauce 950.00 25 20
to-65 Green 100.00 6 10
如果第4列数据小于或等于第5列,则应将数据写入第二个文件。
我尝试了以下代码,但在第二个文件中只保存了‘to-56 Olive’。我想不出我到底做错了什么。
file1=open("inventory.txt","r")
file2=open("purchasing.txt","w")
data=file1.readline()
for line in file1:
items=data.strip()
item=items.split()
qty=int(item[3])
reorder=int(item[4])
if qty<=reorder:
file2.write(item[0]+" "+item[1]+"
")
file1.close()
file2.close()
推荐答案
我稍微更改了您的代码,您所需要做的就是迭代文件中的行-如下所示:
file1=open("inventory.txt","r")
file2=open("purchasing.txt","w")
# Iterate over each line in the file
for line in file1.readlines():
# Separate each item in the line
items=line.split()
# Retrieve important bits
qty=int(items[3])
reorder=int(items[4])
# Write to the file if conditions are met
if qty<=reorder:
file2.write(items[0]+" "+items[1]+"
")
# Release used resources
file1.close()
file2.close()
以下是Purchasing.txt中的输出:
to-56 Olive
to-65 Green
这篇关于从文件中读取并写入到另一个python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文