我知道有一些主题告诉我们使用.strip()或.rstrip()函数来执行此操作,但它不适用于我。
我有一个程序在csv文件中附加一个新行,但不幸的是它会生成一个尾随逗号... 我试图在python中使用.strip()函数将其删除但是它运行不正常,我做错了什么? 这是我输入' T123'对于Bike_No和' 05/08/2017' for Purchase_Date
from datetime import datetime
td= datetime.now()
initial_bike_detaillist=[]
deBatt =100
deKM = 0.00
deDate = str(td)[8:10] + "/"+ str(td)[5:7] + "/"+ str(td)[0:4]
print("Option 4: Add abicycle \n")
Bike_No=input("Bike No. :")
Purchase_Date=str(input("Purchase Date:"))
initial_bike_detaillist=[str(Bike_No),str(Purchase_Date),str(deBatt),str(deDate),str(deKM)]#because there is no write function for int
filename="Assignment_Data1.csv"
file=open(filepath + filename,"a")
file.write("\n")
for k in initial_bike_detaillist:
file.write("{},".format(k))
print("Bicycle ({}) has been created".format(Bike_No))
file.close()
file=open(filepath + filename,"r")
for line in file:
line.strip()
print(line)
预期产出=
Bike No.,Purchase Date,Batt %,Last Maintenance,KM since Last
T101,10/04/2016,55,10/01/2017,25.08
T102,01/07/2016,10,15/05/2017,30.94
T103,15/11/2016,94,13/06/2017,83.16
T104,25/04/2017,58,10/01/2017,25.08
T105,24/05/2017,5,20/06/2017,93.80
T123,04/04/2017,100,05/08/2017,0.0
实际输出:
Bike No.,Purchase Date,Batt %,Last Maintenance,KM since Last
T101,10/04/2016,55,10/01/2017,25.08
T102,01/07/2016,10,15/05/2017,30.94
T103,15/11/2016,94,13/06/2017,83.16
T104,25/04/2017,58,10/01/2017,25.08
T105,24/05/2017,5,20/06/2017,93.80
T123,04/04/2017,100,05/08/2017,0.0,
`
答案 0 :(得分:2)
而不是这一行:
for k in initial_bike_detaillist:
file.write("{},".format(k))
使用以下行:
file.write(','.join(initial_bike_detaillist))
您的代码:
from datetime import datetime
td = datetime.now()
initial_bike_detaillist = []
deBatt = 100
deKM = 0.00
deDate = str(td)[8:10] + "/" + str(td)[5:7] + "/" + str(td)[0:4]
print("Option 4: Add abicycle \n")
Bike_No = input("Bike No. :")
Purchase_Date = str(input("Purchase Date:"))
initial_bike_detaillist = [str(Bike_No), str(Purchase_Date), str(deBatt), str(deDate),
str(deKM)] # because there is no write function for int
filename = "Assignment_Data1.csv"
file = open(filepath + filename, "a")
file.write("\n")
# for k in initial_bike_detaillist:
# file.write("{},".format(k))
file.write(','.join(initial_bike_detaillist)) # use this line .
print("Bicycle ({}) has been created".format(Bike_No))
file.close()
file = open(filepath + filename, "r")
for line in file:
# line.strip() # Then, not need this line
print(line)