您如何摆脱 CSV 文件中的空白? [复制]
Posted
技术标签:
【中文标题】您如何摆脱 CSV 文件中的空白? [复制]【英文标题】:How do you get rid of the gaps in the CSV file? [duplicate] 【发布时间】:2017-04-13 20:22:03 【问题描述】:当我运行我的程序时,在空白的 CSV 文件中,每个产品之间似乎有一行空白。你如何摆脱这个差距? (如第一张图所示)
This is what happens when I fully run my code
This is my original CSV file that contains all the product information. Row A is the GTIN-8 code, row B is the product name, C is the current stock level, D is the re-order stock level, and E is the target stock level (Just to clarify)
这是我的代码:
import csv
redo='yes'
receipt=open('receipt.txt', 'wt')
stock=open('Stock_.csv', 'rt')
stock_read=csv.reader(stock)
blank_csv=open('Blank_csv_.csv', 'wt')
blank_csv_write=csv.writer(blank_csv)
clothes=(input('\nPlease enter the GTIN-8 code of what you want to purchase: '))
quantity=int(input('\nPlease enter the amount of this product you want to buy: '))
for row in stock_read:
GTIN=row[0]
product=row[1]
current=row[2]
re_order=row[3]
target=row[4]
if clothes==GTIN:
current=int(current)-quantity
blank_csv_write.writerows([[GTIN,product,current,re_order,target]])
stock.close()
blank_csv.close()
reorder_receipt=open('receipt.txt', 'wt')
blank_csv2=open('Blank_csv_.csv', 'rt')
blank_csv_read2=csv.reader(blank_csv2)
stock_check=input('Press \"ENTER\" if you want to check the current stock leavels: ')
if stock_check=='':
for row in blank_csv_read2:
for field in row:
GTIN=row[0]
product=row[1]
current=int(row[2])
re_order=int(row[3])
target=int(row[4])
if current<=re_order:
re_stock=target-current
reorder_receipt.write(GTIN+' '+product+' '+str(current)+' '+str(re_order)+' '+str(target)+' '+str(re_stock)+'\n')
blank_csv2.close()
reorder_receipt.close()
提前谢谢你!!!!
【问题讨论】:
是否有机会使用 blank_csv_write.writerow([GTIN,product,current,re_order,target]) 而不是 writerows 解决问题? (注意我删除了一对括号) 【参考方案1】:我没有深入研究您的代码,但乍一看,如果您想删除每行数据之间的多余行,请从 reorder_receipt 末尾删除换行符 '\n' .write() 函数调用。
也就是说,修改:
reorder_receipt.write(GTIN+' '+product+ ... +str(re_stock)+'\n')
成为:
reorder_receipt.write(GTIN+' '+product+ ... +str(re_stock))
【讨论】:
【参考方案2】:我想问题出在target=row[4]
上。
可能是“目标”字符串得到了一个额外的 \n。所以剥离它可能会解决问题。
target.strip()
【讨论】:
【参考方案3】:这似乎与THIS 问题重复。我相信那里的答案将帮助您解决问题。提示:换行=''
【讨论】:
以上是关于您如何摆脱 CSV 文件中的空白? [复制]的主要内容,如果未能解决你的问题,请参考以下文章