我需要根据用户输入添加到.csv文件。代码的其他部分添加到文件中,但我不知道如何添加用户输入。我是python和编码的新手。
我的代码的其他部分可以合并或从.csv数据库中提取数据并将其写入单独的文件,但无法弄清楚如何通过多个用户输入将其写入或追加到文件中。外发文件。
def manualentry():
stock = input("Enter Stock #: ") #Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") #Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) #Prints the line of user data
input4 = input("Append to inventory list? Y/N") #Asks user to append the data to the output file.
if input4 == "Y" or input4 == "y":
with open('INV.csv','a', newline='') as outfile: #Pull up a seperate csv to write to, an output for collected data
w = csv.writer(outfile) #Need to write the user input to the .csv file.
w.writerow([stock, VIN, make, model, year, l8v]) #<-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
starter() #Restarts whole program from begining.
if input4 == "N" or input4 == "n":
print("SKIPPING. RESTARTING....")
starter() #Reset
else:
print("Invalid entry restarting program.")
starter() #Reset
starter() #R E S E T !
只需要将用户输入应用于.csv并保存在此即可。这段代码的早期部分可以正常运行,但可以添加到.csv文件中。是要填写丢失的数据,否则这些数据将不会在单独的数据库中列出。
答案 0 :(得分:0)
代码有一些改进。
while
或for
来代替递归stop
来停止循环,关闭文件并退出str.lower() == 'y'
来覆盖y
和Y
的大小写形式代码将如下所示
import csv
def manualentry():
#Open csv file at start
outfile = open('INV.csv', 'a', newline='')
w = csv.writer(outfile) # Need to write the user input to the .csv file.
#Everything wrapped in a while True loop, you can change to any loop accordingly
while True:
stock = input("Enter Stock #: ") # Generate data for each column to fill in to the output file.
VIN = input("Enter Full VIN: ") # Each line asks the user to add data do the line.
make = input("Enter Make: ")
model = input("Enter Model: ")
year = input("Enter Year: ")
l8v = input("Enter L8V: ")
print(stock, VIN, make, model, year, l8v) # Prints the line of user data
input4 = input("Append to inventory list? Y/N") # Asks user to append the data to the output file.
if input4.lower() == "y":
w.writerow([stock, VIN, make, model, year, l8v]) # <-This is the portion that seems to fall apart.
print("INVENTORY UPDATED")
if input4.lower() == "n":
print("SKIPPING. RESTARTING....")
#If you see stop, stop writing, close the file and exit
if input4.lower() == 'stop':
print('Not writing anymore! Stopping')
outfile.close()
exit()
else:
print("Invalid entry restarting program.")
#Call manualentry
manualentry()
答案 1 :(得分:0)
您可以简单地使用用户控制的while循环来递归地获取用户输入,然后可以根据用户选择退出
user_input = 'Y'
while user_input.lower() == 'y':
# Run your code here
user_input = input('Do you want to add one more entry: Enter [Y/N]')
答案 2 :(得分:0)
尝试一下
RowsAffected