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

从文件读取并写入另一个python,python,file-handling,Python,File Handling,我有一个包含以下内容的文件, 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=file

我有一个包含以下内容的文件,

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()
file1=open(“inventory.txt”、“r”)
file2=打开(“purchasing.txt”、“w”)
data=file1.readline()
对于文件1中的行:
items=data.strip()
item=items.split()
数量=整数(项目[3])
重新排序=整数(项目[4])

如果qty我稍微更改了您的代码,您所需要做的就是迭代文件中的行-如下所示:

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

# Release used resources
file1.close()
file2.close()

您只读取了一行输入。因此,您最多可以有一行输出

我看你的代码有点“老派”。这是一个更“现代”和更像蟒蛇的版本

# 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')
#打开文件的现代方式。收尾处理得很干净
在文件中打开('inventory.txt',mode='r')\
打开('purchasing.txt',mode='w')作为输出文件:
#文件是可编辑的
#我们可以用一个简单的for循环读取每一行
对于\u文件中的行:
#元组解包更具python风格和可读性
#而不是使用索引
ref,name,price,quantity,reorder=line.split()
#将字符串转换为整数
数量,再订购=整数(数量),整数(再订购)

如果您正在执行的是
data.strip()
而不是
line.strip()
。另外,还要去掉
data=file1.readline()
,因为它正在使用第一行,但不使用它,而且实际上不需要
.strip()
,因为
.split()
删除了所有空白。@Upeka Fernando您可以使用append方法在“purchasing.txt”中写入项,因为write可以覆盖它。您可以将file2=open(“purchasing.txt”,“w”)更改为file2=open(“purchasing.txt”,“a”),然后我想您可以解决这个问题。IME,我无法获得一个健壮的“a”模式,因此将文件读取到内存中,然后将处理后的数据写入“w”模式文件。@ShivamKumar正常的“w”模式在这里很好。仅当您希望将新数据附加到现有文件时,才需要“a”模式。我有时会看到这样的代码:在循环中以“a”模式重复打开文件,写入一行,然后在每次循环迭代中关闭文件。这是非常低效的,而且只有在数据必须在脆弱的环境中写入时才应该这样做,因为在这种环境中,系统经常面临崩溃的危险。即使这样,你也有数据损坏的风险……干得好。然而,OP的问题本质上是一个打字错误,这些问题在几天后就被删除了,因为它们不太可能帮助未来的读者:即使它们有完全相同的问题,它们也不太可能找到这个问题。这通常是自动发生的,但投票或接受的答案会阻止自动过程,所以我们必须手动删除它。@PM2Ring谢谢,以后再说-在这种情况下,我应该发布答案吗,还是忽略?如果你可以在评论中指出错别字,那么就这样做。如果问题太复杂,无法在评论中描述,请随意写一个适当的答案,但请注意,如果问题被删除,您将失去任何代表性。谢谢您,布鲁诺!我一直在寻找这个“带有open…”语法
# 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')