【问题标题】:Read from file and write to another python从文件中读取并写入另一个 python
【发布时间】:2018-10-30 07:26:52
【问题描述】:

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

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()

【问题讨论】:

  • 您正在使用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”模式下在循环中重复打开文件,写入一行,然后在每次循环迭代时关闭文件。这是非常低效的,并且只有当数据必须在系统经常处于崩溃危险的脆弱环境中写入时才应该这样做。即便如此,您仍然冒着数据损坏的风险......

标签: python file-handling


【解决方案1】:

您只读取一行输入。所以,你最多只能有一行输出。

我看到您的代码有点“老派”。这是一个更“现代”的 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')

【讨论】:

  • 谢谢你,布鲁诺!我正在寻找这种“开放式...”语法
【解决方案2】:

我稍微修改了你的代码,你需要做的就是遍历文件中的行——就像这样:

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()

这是purchasing.txt中的输出:

to-56   Olive
to-65   Green

【讨论】:

  • 干得好。然而,OP 的问题本质上是一个错字,并且这些问题在几天后被删除,因为它们不太可能帮助未来的读者:即使他们有完全相同的问题,他们也不太可能找到这个问题。这通常会自动发生,但投票或接受的答案会阻止该自动过程,因此我们必须手动将其删除。
  • @PM2Ring 谢谢,为了未来 - 我应该在这种情况下发布答案,还是忽略?
  • 如果您可以在评论中指出错字,那么就这样做。如果在评论中描述太复杂,请随意写一个正确的答案,但请注意,如果问题被删除,您将失去任何获得的代表。
猜你喜欢
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2015-12-29
  • 2012-10-22
相关资源
最近更新 更多