【问题标题】:Split data into multiple files: how to handle (unknown number of) multiple connections将数据拆分为多个文件:如何处理(未知数量)多个连接
【发布时间】:2019-01-15 21:10:27
【问题描述】:

我想将一个(在现实生活中:巨大的)文件拆分为多个文件,这些文件由数据中的第二列指定。 IE。在下面的示例中,我需要文件 431.csvrr1.csv。 我的主要想法是打开新连接以写入如果尚未打开 - 打开连接的记录在字典 files_dict 中,然后遍历它并最终关闭。

我被困在如何逐行引用这些连接。

在现实生活中,这些文件名(第二列)的数量和值是事先不知道的。

在这里找到了一些灵​​感:

write multiple files at a time

python inserting variable string as file name

How can I split a text file into multiple text files using python?

data_in中的玩具数据内容:

123,431,t
43,rr1,3
13,rr1,43
123,rr1,4

到目前为止我的幼稚伪代码:

files_dict = dict() #dict of file names

with open(data_in) as fi:
    for line in fi:
        x = line.split(',')[1]

        if x not in files_dict:
            fo = x + '.csv'
            files_dict[x] = fo

            '''
            open files_dict[x]
            write line to files_dict[x]

            '''
    else:
        '''
        write line to files_dict[x]
        '''

for fo in files_dict.fos:
    fo.close()

【问题讨论】:

  • 您可以在 pandas 中用几行代码完成此操作。给我一秒钟写一个解决方案。或者其他人可能因为我在办公室。

标签: python file-io split


【解决方案1】:

您确实有正确的想法,但是您应该将文件对象而不是文件名存储在 dict 中,并且您不需要 else 块(应该与 if 对齐而不是for):

files_dict = {}

with open(data_in) as fi:
    for line in fi:
        x = line.split(',')[1]
        if x not in files_dict:
            files_dict[x] = open(x + '.csv', 'w')
        files_dict[x].write(line)

for file in files_dict.values():
    file.close()

【讨论】:

  • 天哪! - 这正是我想要的。刚接触python,我没有考虑文件对象本身。
【解决方案2】:

file 对象本身放入字典中,而不是文件名。

files_dict = {}

with open(data_in) as fi:
    for line in fi:
        x = line.split(',')[1]

        if x not in files_dict:
            fo = open(x + '.csv', "w")
            files_dict[x] = fo
        else:
            fo = files_dict[x]

        fo.write(x)

for fo in files_dict.values():
    fo.close()

【讨论】:

    【解决方案3】:

    您也可以将 pandas 用于您的大型 csv,因为它可以很好地处理它,然后只需遍历 pandas 列:

    df = pd.read_csv('fun.txt', header=None)
    
    string = "tester string"
    
    for row in df[1]:
        fo = row + '.csv'
        f = open(fo, 'a')
        f.write(string+'\n')
        f.close()
    

    输出是 2 个文件,431.csv 和 rr1.csv。 431.csv的内容:

    tester string
    

    rr1.csv 的内容:

    tester string
    tester string
    tester string
    

    它会将任何添加的信息附加到重复文件中,我觉得这是基于您的伪代码所需的行为。这是一个很好的解决方案,因为它会在遍历列时打开和关闭您的文件。这样您就不会同时打开 50 个文件,这可能会给您的操作系统带来麻烦。

    【讨论】:

    • 既然你说你的文件很大,打开太多文件会导致问题。您的操作系统上有一个 ulimit 可以打开多少个文件。这是一个非常简单的 pandas 实现。我只是发现它是组织 .csv 和 .txt 等文件的一种非常简单的方法,因为它可以处理所有解析并允许轻松访问特定列。
    • 如果让它们保持打开状态不是问题,您也可以等待在循环之外关闭文件。
    猜你喜欢
    • 2019-03-29
    • 2023-03-16
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多