Чтение из файла и запись в другой питон - PullRequest
0 голосов
/ 20 мая 2018

У меня есть файл с содержимым, как указано ниже,

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

Ответы [ 2 ]

0 голосов
/ 20 мая 2018

Вы читаете только одну строку ввода.Таким образом, вы можете иметь не более одной строки вывода.

Я вижу, что ваш код немного "старой школы".Вот более «современная» и 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')
0 голосов
/ 20 мая 2018

Я чуть-чуть изменил ваш код, все, что вам нужно сделать, это перебрать строки в вашем файле - например, так:

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

Вот вывод в purchase.txt :

to-56   Olive
to-65   Green
...