将多个列表写入csv. Python中的文件 [英] Write multiple lists into csv. file in Python

查看:211
本文介绍了将多个列表写入csv. Python中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python(以及所有程序设计)的新手.我编写了一个简短的程序,将专用文件夹的文件名读取为字符串.之后,我提取"文件名中的信息(例如文档编号,标题等->在示例中稍后称为value1,value 2等).

I am new to Python (and to programming at all). 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 (e.g. document number, title etc. -> later referred as value1, value 2, etc in the example).

之后,我将值存储到列表中.每个文件的一个列表(通过循环生成)如下所示: ['value1','value 2','value3']

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']

通过打印",我可以根据需要显示列表:

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)

现在我要像这样将列表存储到csv.file中:

Now I want to store the lists into a csv.file like this:

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.

我尝试过的一次尝试:

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是在其中定义列表的变量) 有了这段代码,我得到:

(list2 is the variable in which the list is defined) With this code I get:

value1
value2
value3
...

我希望需要一个循环,但是我无法解决这个问题.

I expect that a loop is required, but I can't get my head around it.

推荐答案

您可以构造一个列表列表,然后将其传递给csv.writer.writerows().每个嵌套列表都对应于从每个文件名中提取的值.针对这样的数据结构:

You can construct a list of lists which can then be passed to 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可以使用csv.writer,writerows(data)直接写入CSV文件.这是一些应该执行您想要的代码:

data can be written directly to a CSV file using csv.writer,writerows(data). 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)

此代码建立一个列表列表(data),然后通过一次操作将其写入CSV文件.上面代码的一种改进是使用列表推导为每个文件名创建值列表,并将其直接附加到data列表.这样会更高效并且使用更少的代码,但是也许第一个示例对您来说更容易理解:

This code builds up a list of lists (data) which is then written to a CSV file in one operation. 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. 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)

这篇关于将多个列表写入csv. Python中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆