将数据附加到 Python 中的文件

Appending data to a file in Python

我得到的错误是 write() 只接受一个参数(给定 5 个)。我能够通过在每一行上写一个写语句来使写工作正常进行,但这导致每个输入都被写在一个新行上。我想要做的是以类似于为临时文件创建的 table 的格式进行写入。我不确定我将如何实现实现这一目标的逻辑。

import os
def main ():
    temp_file = open('temp.txt', 'a')
    temp_file.write('Product Code | Description | Price' + '\n'
    'TBL100 | Oak Table | 799.99' + '\n'
    'CH23| Cherry Captains Chair | 199.99' + '\n' 
    'TBL103| WalnutTable |1999.00' + '\n'
    'CA5| Chest Five Drawer| 639' + '\n')

    another = 'y'
    # Add records to the file.
    while another == 'y' or another == 'Y':

        # Get the coffee record data.
        print('Enter the following furniture data:')
        code = input('Product code: ')
        descr = input('Description: ')
        price = float(input('Price: '))

        # Append the data to the file.
        temp_file.write(code, print('|'), descr, print('|'), str(price) + '\n')

        # Determine whether the user wants to add
        # another record to the file.
        print('Do you want to add another record?')
        another = input('Y = yes, anything else = no: ')

        # Close the file.
        temp_file.close()
        print('Data appended to temp_file.')

你应该只通过一个参数写一行

temp_file.write(f'{code} | {descr} | {price}\n') 

在您的代码中,只需替换此行

temp_file.write(code, print('|'), descr, print('|'), str(price) + '\n') 

通过这条线

temp_file.write(code + '|' + descr + '|' + str(price) + '\n')

Explanations: The method write takes one argument, but you provide five in your code. That is the reason of the error you have got. You just have to concatenate your variables to get one string that you will pass to the method.