简体   繁体   English

将多个列表写入csv。 Python文件

[英]Write multiple lists into csv. file in Python

I am new to Python (and to programming at all). 我是Python(以及所有编程)的新手。 I have written a short program that reads filenames of a dedicated folder into strings. 我编写了一个简短的程序,将专用文件夹的文件名读取为字符串。 After that I 'extract' information which is in the file names (eg document number, title etc. -> later referred as value1, value 2, etc in the example). 之后,我“提取”文件名中的信息(例如,文档编号,标题等->稍后在示例中称为value1,value 2等)。

After that I store the values into lists. 之后,我将值存储到列表中。 One list for each file (generated with a loop) which looks like this: ['value1','value 2', 'value3'] 每个文件的一个列表(通过循环生成)如下:['value1','value 2','value3']

with 'print' I get the lists displayed as I want them: 使用“打印”,我得到想要显示的列表:

[‘value1‘, ‘value 2‘, 'value3'] (# generated from file 1)
[‘value1‘, ‘value 2‘, 'value3'] (# generated from file 2)
[‘value1‘, ‘value 2‘, 'value3'] (# generated from file 3)
[‘value1‘, ‘value 2‘, 'value3'] (# generated from file 4)
[‘value1‘, ‘value 2‘, 'value3'] (# generated from file 5)

Now I want to store the lists into a csv.file like this: 现在,我想将列表存储到这样的csv.file中:

value1, value2, value3, (# generated from file 1)
value1, value2, value3, (# generated from file 2)
value1, value2, value3, (# generated from file 3)
value1, value2, value3, (# generated from file 4)
value1, value2, value3, (# generated from file 5)

I have searched the web for possible solutions. 我已经在网上搜索了可能的解决方案。 I have tried severals things but just get the last list which was generated. 我已经尝试了几样东西,但是只获取了生成的最后一个列表。

one Attempt that I have tried: 我尝试过的一次尝试:

import os
import csv

def go():
    folder = folderentry.get()  # reads path for 'folder'

    for path, subdirs, files in os.walk(folder):
        for name in files:



            searchValue1 = name.find("value1")

            if searchValue1 >= 0:
                parameter1 = "value 1"       
            else:
                parameter = "NOT FOUND!"


            searchValue2 = name.find("value2")

            if searchValue1 >= 0:
                parameter2 = "value 2"       
            else:
                parameter = "NOT FOUND!"


            searchValue3 = name.find("value3")

            if searchValue3 >= 0:
                parameter3 = "value 3"       
            else:
                parameter = "NOT FOUND!"


            list2 = []
            list2.append(parameter1)
            list2.append(parameter2)
            list2.append(parameter3)

            print(list2) # delivers the lists lik I want them


            # generate csv.file:
            with open('some.csv', 'wb') as f:
                writer = csv.writer(f)
                list3 = zip(list2)
                writer.writerows(list3)

(list2 is the variable in which the list is defined) With this code I get: (list2是在其中定义列表的变量)使用此代码,我得到:

value1
value2
value3
...

I expect that a loop is required, but I can't get my head around it. 我希望这是一个循环,但我无法解决。

The issue is with the lines - 问题在于线路-

with open('some.csv', 'wb') as f:  #Using `w` mode overwrites the file everytime
    ...
    list3 = zip(list2)   #This does not do what you think it does.
    writer.writerows(list3)  #This expects a list of rows, and writes each row on a single line.

First of all, list2 is a 1-dimensional list of strings (according to what you have created. When using zip() directly on such lists, you get a list of tuples back, with each tuple having each element. Example - 首先, list2是一维字符串列表(根据您创建的字符串而定。直接在此类列表上使用zip() ,会返回一个元组列表,每个元组都有每个元素。示例-

>>> zip(['asd','sdf','dfg'])
[('asd',), ('sdf',), ('dfg',)]

You do not need to do this. 您不需要这样做。 Secondly, after this you use writer.writerows() , this writes each tuple in your list3 into a single line, considering each tuple as a row. 其次,在此之后,您使用writer.writerows() ,这会将list3每个元组写入一行, list3每个元组视为一行。 You want to use writer.writerow() here . 您要在此处使用writer.writerow() Example - 范例-

with open('some.csv', 'ab') as f:
    writer = csv.writer(f)
    writer.writerow(list2)

You can construct a list of lists which can then be passed to csv.writer.writerows() . 您可以构造一个列表列表,然后将其传递给csv.writer.writerows() Each of the nested lists corresponds to the values extracted from each file name; 每个嵌套列表都对应于从每个文件名中提取的值。 aim for a data structure like this: 目标是这样的数据结构:

data = [['value1', 'value 2', 'value3'],
        ['value1', 'value 2', 'value3'],
        ['value1', 'value 2', 'value3']]

data can be written directly to a CSV file using csv.writer,writerows(data) . 可以使用csv.writer,writerows(data)data直接写入CSV文件。 Here is some code that should do what you want: 这是一些应该执行您想要的代码:

import os
import csv

def go():
    search_strings = ('value1', 'value2', 'value3')    # target strings to be found in file name
    data = []
    folder = folderentry.get()  # reads path for 'folder'

    for path, subdirs, files in os.walk(folder):
        for name in files:
            extracted_strings = []
            for s in search_strings:
                if s not in name:
                    s = 'NOT FOUND!'
                extracted_strings.append(s)
            data.append(extracted_strings)

    with open('some.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(data)

This code builds up a list of lists ( data ) which is then written to a CSV file in one operation. 这段代码建立了一个列表( data )列表,然后通过一次操作将其写入CSV文件。 A refinement of the code above is to use a list comprehension to create the value list for each file name and append it directly to the data list. 上面代码的一种改进是使用列表推导为每个文件名创建值列表,并将其直接附加到data列表中。 This is more efficient and uses less code, but perhaps the first example is more understandable to you: 这效率更高并且使用的代码更少,但是第一个示例也许对您更容易理解:

import os
import csv

def go():
    search_strings = ('value1', 'value2', 'value3')    # target strings to be found in file name
    data = []
    folder = folderentry.get()  # reads path for 'folder'

    for path, subdirs, files in os.walk(folder):
        for name in files:
            data.append([s if s in name else 'NOT FOUND!' for s in search_strings])

    with open('some.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(data)

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

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