简体   繁体   English

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

[英]Read from file and write to another python

I have a file with contents as given below,我有一个包含如下内容的文件,

to-56  Olive  850.00  10 10
to-78  Sauce  950.00  25 20
to-65  Green  100.00   6 10

If the 4th column of data is less than or equal to the 5th column, the data should be written to a second file.如果第 4 列数据小于或等于第 5 列,则应将数据写入第二个文件。
I tried the following code, but only 'to-56 Olive' is saved in the second file.我尝试了以下代码,但只有“to-56 Olive”保存在第二个文件中。 I can't figure out what I'm doing wrong here.我无法弄清楚我在这里做错了什么。

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

You're reading only one line of input.您只阅读一行输入。 So, you can have at most one line of output.因此,您最多可以有一行输出。

I see that your code is a bit "old school".我看到你的代码有点“老派”。 Here's a more "modern" and Pythonic version.这是一个更“现代”和 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')

I've changed your code a tiny bit, all you need to do is iterate over lines in your file - like this:我已经稍微更改了您的代码,您需要做的就是遍历文件中的行 - 像这样:

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

Here is the output in purchasing.txt :这里是purchasing.txt输出:

to-56   Olive
to-65   Green

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM