简体   繁体   English

字符串封装行时的Python csv.reader

[英]Python csv.reader when line is encapsulated by strings

I am attempting to read a csv file. 我正在尝试读取一个csv文件。

    with open(os.path.join(folder,mfile),'r') as csvfile:
        fileReads = csv.reader(csvfile, delimiter=',')

        for i, line in enumerate(fileReads):
            print 'line[{}] = {}'.format(i, line)

Unfortunately, my data is contained in the following format in the CSV file: 不幸的是,我的数据以以下格式包含在CSV文件中:

"val1, val2, val3"

(including quotes, don't ask why this is the case...) (包括引号,不要问为什么会这样...)

This results in the csv.reader returning the entire line as one value - so the output to the console is something like 这导致csv.reader将整行作为一个值返回-因此向控制台的输出类似于

line[1] = ['val1,val2,val3']

as would be expected. 不出所料。

  • How can I correctly read this CSV file? 如何正确读取此CSV文件?

Wrap the file in a generator function to strip quotes: 将文件包装在生成器函数中以去除引号:

def strip_quotes(iterable):
    for line in iterable:
        yield line.rstrip('\n').strip('"') + '\n'

then use that function like: 然后使用如下功能:

fileReads = csv.reader(strip_quotes(csvfile), delimiter=',')

The csv.reader() class happily takes any iterable object, not just files. csv.reader()类愉快地接受任何可迭代的对象,而不仅仅是文件。

The strip_quotes() function can be adjusted to fit your specific file contents. 可以调整strip_quotes()函数以适合您的特定文件内容。 If there are quotes around columns as well, you could remove just one quote from the start and end of the line, for example. 例如,如果列周围也有引号,则可以仅从行的开头和结尾删除一个引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM