8

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.
I tried the following code, but only 'to-56 Olive' is saved in the second file. 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()
sshashank124
  • 31,495
  • 9
  • 67
  • 76
Upeka Fernando
  • 85
  • 1
  • 1
  • 6
  • 2
    You are doing `data.strip()` instead of `line.strip()`. Also get rid of the `data=file1.readline()` since it's consuming the first line but not doing anything with it – sshashank124 May 20 '18 at 13:27
  • And you don't actually need `.strip()` since `.split()` removes all whitespace. – PM 2Ring May 20 '18 at 13:29
  • @Upeka Fernando you can use append method to write item in "purchasing.txt", because write can override it. You can change file2=open("purchasing.txt","w") to file2=open("purchasing.txt","a") then i think you resolve the problem. – Shivam Kumar May 20 '18 at 13:30
  • IME, I couldn't get a robust "a" mode so have read files into memory then written the processed data to a "w" mode file. – John May 20 '18 at 13:31
  • @ShivamKumar Normal "w" mode is fine here. "a" mode is only needed if you want to append fresh data to an existing file. I sometimes see code where a file is repeatedly opened in a loop in "a" mode, a line is written, then the file is closed, on every loop iteration. That's very inefficient, and should only be done if the data _must_ be written in a fragile environment where the system is constantly in danger of crashing. And even then you risk data corruption anyway... – PM 2Ring May 20 '18 at 13:35

2 Answers2

31

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.

# 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')
Bruno L
  • 839
  • 5
  • 9
5

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:

to-56   Olive
to-65   Green
Kacperito
  • 1,277
  • 1
  • 10
  • 27
  • Nice work. However, the OP's problem was essentially a typo, and such questions get removed after a few days since they are unlikely to help future readers: even if they have the exact same problem they're unlikely to find this question. That normally happens automatically, but upvoted or accepted answers block that automatic process, so we have to delete it manually. – PM 2Ring May 20 '18 at 14:13
  • @PM2Ring Thanks, for future - should I post the answers in such cases anyway, or just ignore? – Kacperito May 20 '18 at 14:28
  • If you can point out the typo in a comment, then just do that. If it's too complicated to describe in a comment, feel free to write a proper answer, but be aware that you will lose any rep gained if the question gets deleted. – PM 2Ring May 20 '18 at 14:53