使用Python格式化以制表符分隔的文本文件
我正在将Python脚本从2更新到3。它读取清单(即[batchdate]xmlList.xml),遍历清单中标识的每个xml文件,收集统计数据,然后以制表符分隔的文本格式输出统计数据文件。选项卡文件的格式和编码已关闭,我不知道如何修复它 对于utf-8编码:使用Python格式化以制表符分隔的文本文件,python,Python,我正在将Python脚本从2更新到3。它读取清单(即[batchdate]xmlList.xml),遍历清单中标识的每个xml文件,收集统计数据,然后以制表符分隔的文本格式输出统计数据文件。选项卡文件的格式和编码已关闭,我不知道如何修复它 对于utf-8编码: class UnicodeWriter: def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): self.qu
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
self.queue = StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
def writerow(self, row):
self.writer.writerow([str(s).encode("utf-8") for s in row])
data = self.queue.getvalue()
self.stream.write(data)
self.queue.truncate(0)
在xmllist.xml清单中读取:
xmlListPath = input('Enter the filepath of the xmlList.xml file: ').replace('"', '')
xmlListFile = codecs.open(xmlListPath)
xmlList = etree.parse(xmlListFile)
listRoot = xmlList.getroot()
xmlListFile.close()
创建统计文件并写入标题:
batchID = path.split(xmlListPath)[1]
statsFile = 'S:/Metadata/ETD/Documentation/Statistics/' + batchID.replace('xmlList.xml', '.stats.txt')
stats = open(statsFile, 'w')
wtrStats = UnicodeWriter(stats, delimiter='\t')
statsHeader = ['Author', 'Degree', 'Department', 'Embargo Start Date', 'Date Web Available',
'Embargo Code', 'Identifier', 'PURL', 'Title', 'Comments']
wtrStats.writerow(statsHeader)
下面是选项卡文件的显示方式:
b'Author' b'Degree' b'Department' b'Embargo Start Date' b'Date Web Available' b'Embargo Code' b'Identifier' b'PURL' b'Title' b'Comments'
b'Confer, Matthew Phelan' b'Ph.D.' b'Chemical & Biological Engineering' b'01/01/2021' b'01/01/2026' b'4' b'u0015_0000001_0003682' b'http://purl.lib.ua.edu/177826' b'EXPERIMENTAL AND COMPUTATIONAL STUDIES OF MATERIALS DECOMPOSITION' b''
感谢您的帮助。在Python3中,CSV模块读取器和编写器希望找到字符串(unicode文本)-当您向它们输入字节时,通过对字符串进行预编码,它使用这些字节对象的表示形式,即
b'…'
前缀字符串
TL;DR:只需以所需的编码打开输出文件,并将您的csv.writer
对象指向它-绝对不需要您列出的UnicodeWriter
中间类
import csv
...
stats = open(statsFile, 'w', encoding="utf-8")
wtrStats = csv.writer(stats, delimiter="\t")
...
标签文件应该是什么?为什么在执行self.writer.writerow()操作之前要转换为字节?这就是把
b
和撇号放在每个列标题上的原因。我觉得有趣的是,你的答案有一半是TL;部分博士:)谢谢你的咯咯笑。事实上,这就是全部答案。只有一个额外的前言。