为了账号安全,请及时绑定邮箱和手机立即绑定

使用python使用文件名信息将一列批量插入到CSV中

使用python使用文件名信息将一列批量插入到CSV中

拉莫斯之舞 2023-05-16 14:57:47
我有 169 个具有相同结构(90 列具有相同标题)和相同命名系统的 CSV 文件。文件名截图这些文件被命名为:2019-v-12019-v-22019-v-3ETC。对于每个 CSV,我想添加一列,标题为“访问”,并且该列中的值取自文件名(末尾的数字,第二个破折号之后)。因此,例如,第一个 CSV 将有一个名为“访问”的新列,其中每一行在该列中都被赋予值“1”。如果有 Python 解决方案,那就太棒了。我没有编码背景,这是我唯一有点熟悉的语言,但我自己似乎无法弄清楚这门语言。任何帮助将不胜感激 - 谢谢!
查看完整描述

2 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

import pandas as pd

import os


def csv_folder_input(path,folder):

    path = os.path.join(path,folder)

    os.chdir(path)

    counter=1

    for filename in os.listdir(path):

        if filename.endswith(".csv"):

             with open(filename, 'r') as csvfile:

             counter=counter+1

             df = pd.read_csv(csvfile)

             df['Visits']=int(filename.split('_')[2].split('.')[0])

             df.to_csv(filename)

       

csv_folder_input(your path name,your folder name)

输入您的路径名,然后输入您的文件夹名称。我可以看到你的文件夹名称是 2019-v。在文件夹前输入适当的路径名,并确保输入适用于 MacOS 的正确路径格式。我相信它应该可以正常工作。


查看完整回答
反对 回复 2023-05-16
?
侃侃无极

TA贡献2051条经验 获得超10个赞

首先,您需要一个文件列表:


from os import listdir

from os.path import isfile, join

import csv       # You'll need this for the next step


mypath = 'path/to/csv/directory'

allfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

然后你想打开每个文件,添加列,然后再次保存。


from os import listdir

from os.path import isfile, join

import csv


mypath = 'path/to/csv/directory'

allfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]


for file in allfiles:


  # This will only work if your filenames are consistent.

  # We split the name into a list, ['2019', 'v', '1.csv']

  #   then take the third item (index 2), and remove the

  #   last 4 characters.


  number_at_end = file.split("-")[2][:-4]


  # We open the file...


  with open(file, newline='') as csvfile:

    reader = csv.reader(csvfile)


  # Add the column name to the first row, and

  # add the value to each row...


  for i, row in enumerate(reader):

    if i == 0:

      row.append('Visits')

    else:

      row.append(number_at_end)


  # and then write the file back.


  with open(file, newline='') as csvfile:

    writer = csv.writer(csvfile)

    writer.writerows(reader)


查看完整回答
反对 回复 2023-05-16
  • 2 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信