gpt4 book ai didi

Python:write.csv 添加额外的回车符

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:48 25 4
gpt4 key购买 nike

我正在使用 python 编写 Excl 到 CSV 转换器。我在 Linux 中运行,我的 Python 版本是:Python 2.7.1(r271:86832,2012 年 12 月 4 日,17:16:32)[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] 在 linux2 上

在下面的代码中,当我注释 5 个“csvFile.write”行时,csv 文件生成得很好。但是,使用原样的代码,在“wr.writerow”生成的所有行的末尾添加了一个回车符。

问题:为什么在存在“csvFile.write”时,csv 写入会添加额外的回车?

import sys  # For interacting with the Unix Shell
import os # For OS information (mainly path manipulation)

import time # For data and time
import xlrd # For reading both XLS/XLSX files
import csv # Writing CSV files

# Get the Excel file from cmd line arguments
excelFile = sys.argv[1]

def csv_from_excel(excelFile):
wb = xlrd.open_workbook(excelFile, encoding_override='utf8')
sh = wb.sheet_by_index(0)
print sh.name, sh.nrows, sh.ncols
# Output file
csvFileName= os.path.splitext(excelFile)[0] + '.csv'
# Open file for write
try:
csvFile = open(csvFileName, 'wb')
except IOError:
print "Error: cannot open output CSV file"
# Print a header to the output file
csvFile.write('###########################################################\n')
csvFile.write('# Python Version: %s\n' % (sys.version))
csvFile.write('# Date: %s\n' % time.strftime("%d/%m/%Y, %H:%M:%S"))
csvFile.write('# User: %s\n' % os.getlogin())
csvFile.write('###########################################################\n\n')
# Wite Values
wr = csv.writer(csvFile, delimiter=';')

for rownum in xrange(sh.nrows):
wr.writerow([unicode(val).encode('utf8') for val in sh.row_values(rownum)])

csvFile.close()

if __name__ == "__main__":
csv_from_excel(excelFile)

最佳答案

csv.writer 的默认行终止符是 '\r\n'。明确指定 lineterminator如果你只想要 '\n' 参数:

wr = csv.writer(csvFile, delimiter=';', lineterminator='\n')

关于Python:write.csv 添加额外的回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25613698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com