gpt4 book ai didi

python - 从文件中读取并写入另一个python

转载 作者:行者123 更新时间:2023-11-28 22:18:34 25 4
gpt4 key购买 nike

我有一个文件,内容如下,

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]+"\t"+item[1]+"\n")


file1.close()
file2.close()

最佳答案

您只阅读了一行输入。因此,您最多只能有一行输出。

我看到您的代码有点“老派”。这是一个更“现代”和 Pythonic 的版本。

# Modern way to open files. The closing in handled cleanly
with open('inventory.txt', mode='r') as in_file, \
open('purchasing.txt', mode='w') as out_file:

# A file is iterable
# We can read each line with a simple for loop
for line in in_file:

# Tuple unpacking is more Pythonic and readable
# than using indices
ref, name, price, quantity, reorder = line.split()

# Turn strings into integers
quantity, reorder = int(quantity), int(reorder)

if quantity <= reorder:
# Use f-strings (Python 3) instead of concatenation
out_file.write(f'{ref}\t{name}\n')

关于python - 从文件中读取并写入另一个python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50435295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com