【问题标题】:Skip header from next file跳过下一个文件的标题
【发布时间】:2019-03-04 06:40:53
【问题描述】:

在合并多个 CSV 文件时,我可以从所有文件中获取标题,也可以根本不获取任何标题。我只想要第一个文件的标题,因为所有文件都有相同的标题,我正在合并列下方的列。

我是python的新手。实际上在不同的子文件夹中有 23 个同名的 CSV 文件。我正在使用循环逐行读取它们。我只想要第一个文件头。

这是我的代码:

 import os, sys
`import pathlib

    # Specify directory
    # In your case, you may want something like the following
    my_directory = 'C:/Users/Arijeet/Downloads'
    file = pathlib.Path("out.csv")
    if file.exists ():
      print("file found\nremoving")
      os.remove('out.csv')
    else:
      print("file not find\ncreating")


    counter = 1

    # Start the loop
    for folder, sub_folders, files in os.walk(my_directory):
      for special_file in files:
        if special_file == 'iono_tropo.csv':
          file_path = os.path.join(folder, special_file)


          # Open and read
          with open(file_path) as read_file:
            print('Reading iono_tropo csv file ' + str(counter))
            lines=read_file.readlines()
            with open ("out.csv","a+") as f:
              f.writelines(lines)

            counter += 1

我能做什么?

【问题讨论】:

标签: python python-3.x csv merge header


【解决方案1】:

我不完全明白你的意思,但是如果你想合并一些 csv 并且只保留第一个标题。

with open ("file1.csv", "r") as file:
    data = file.readlines()
    data[-1] += "\n"                #Otherwise data from next file will be on the same line


for filename in ["file2.csv", "file3.csv", "file4.csv", "file5.csv"]:
    with open(filename, "r") as file:
        file.readline()             #Skips the header for all the other files
        data += file.readlines()
        data[-1] += "\n"            #Otherwise data from next file will be on the same line


#Creating the merged file
with open("merged.csv", "w") as merged:
    for line in data:
        merged.write(line)

【讨论】:

  • 让我知道它是否有帮助!
  • 不,它没有帮助。它保留所有标题。合并的文件在两个文件之间有一个行间隙。(带标题)
  • 好吧,很奇怪,它对我的​​ csv 工作正常。我可以获得指向您的 csv 的链接还是您有某种示例文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多