【问题标题】:Looping through all files in a folder and appending a random number to each row in each file using Python循环遍历文件夹中的所有文件,并使用 Python 将随机数附加到每个文件中的每一行
【发布时间】:2014-10-04 20:34:51
【问题描述】:

我正在使用 Pig 生成输出。我想将输出随机分配给 2 个组。 正如你们中的一些人所知,Pig 将 part-m-00000 或 part-r-00000 格式的文件输出到文件夹中。 我想遍历输出文件夹中的所有文件,并为每一行随机分配 0 或 1。

我有作业的代码部分:

     with open('part-r-00000','r') as csvinput:
with open('output2.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput, lineterminator='\n')
    reader = csv.reader(csvinput)

    all = []
    for row in reader:
        row.append(randint(0,1))
        all.append(row)

    for row in reader:
         all.append(row)

    writer.writerows(all)

这绝对有效。 我也有示例输入和输出:

    Sample input:
    0,1,2,1,4,3,3,4,1,1
    2,3,4,1,0,0,1,2,1,1
    0,2,3,1,0,2,3,1,1,1

    Sample output:
    0,1,2,1,4,3,3,4,1,1,0
    2,3,4,1,0,0,1,2,1,1,0
    0,2,3,1,0,2,3,1,1,1,1

但是,我需要找出文件夹中有多少文件,并添加另一个循环来遍历每个文件。 我该怎么做?

【问题讨论】:

    标签: python loops file-io apache-pig


    【解决方案1】:

    您可以只遍历当前目录 (os.getcwd) 中的所有文件 (os.listdir):

    import os
    for filename in os.listdir(os.getcwd()):
        # do your stuff
    

    【讨论】:

      【解决方案2】:
      import os
      for f in os.listdir('/path/to/directory'):
          # do something with f
      

      【讨论】:

        【解决方案3】:

        您可以使用os.listdir() 列出当前目录中的所有文件,或者如果您想扫描单独的目录,可以选择包含路径。然后您可以遍历文件列表:

        import os
        
        filelist = os.listdir()
        
        for file in filelist:
            # do your stuff
        

        【讨论】:

          【解决方案4】:

          如果您希望它与子目录一起使用:

          for subdir, dirs, files in os.walk(root):
              for file in files:
                  # subdir+'/'+file would be the name of each file
          

          编辑: root 将是保存这些文件的文件夹的完整路径

          Iterating through directories with Python

          【讨论】:

            猜你喜欢
            • 2017-01-24
            • 2014-04-24
            • 1970-01-01
            • 1970-01-01
            • 2023-02-26
            • 2013-01-21
            • 2014-11-12
            • 1970-01-01
            • 2012-04-25
            相关资源
            最近更新 更多