在Python中向文件追加数据
我得到的错误是write()只接受一个参数(给定5个)。我能够通过在每一行上写一个write语句来让write工作,但是这导致了每一个输入都被写在一个新行上。我试图做的是以类似于为临时文件创建的表的格式进行写入。我不确定如何实现这一逻辑在Python中向文件追加数据,python,python-3.7,Python,Python 3.7,我得到的错误是write()只接受一个参数(给定5个)。我能够通过在每一行上写一个write语句来让write工作,但是这导致了每一个输入都被写在一个新行上。我试图做的是以类似于为临时文件创建的表的格式进行写入。我不确定如何实现这一逻辑 import os def main (): temp_file = open('temp.txt', 'a') temp_file.write('Product Code | Description | Price' + '\n' 'T
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')
解释:
方法write
接受一个参数,但在代码中提供了五个参数。这就是你犯错误的原因。您只需将变量连接起来,就可以得到一个字符串,并将其传递给方法
你不能只使用
打印
内部写入
本身,只需构建一个包含所有元素的字符串,只需在开始时使用“+”,你可能希望在循环后关闭文件,而不是在文件内部。@khelwood谢谢,我做了调整,我猜这很可能是因为某些参数在关闭循环中的文件时可能会导致错误?我在尝试将多个条目附加到文件时遇到了这个问题。在环路外闭合,这就解决了问题。仍然在学习所有的基础知识。