【问题标题】:Alternate Between Relative and Absolute Path in Same Loop在同一循环中的相对路径和绝对路径之间交替
【发布时间】:2019-12-01 16:05:56
【问题描述】:

我正在尝试:

  1. 循环浏览 CSV 文件目录
  2. 将文件名作为新列附加到每个文件
  3. 将每个文件连接成一个主文件

但是在将绝对路径转换回相对路径时,我在第 3 步卡住了,因为我的输出看起来像 ../../../../Desktop/2018.12.31.csv,而我只是希望它是 2018.12.31

例如,假设目录包含两个文件:2018.12.31.csv2018.11.30.csv

2018.12.31.csv

A B
1 2

2018.11.30.csv

A B
3 4

运行我的程序后:

import os
import pandas as pd

folder = ('/Users/user/Desktop/copy')
files = os.listdir(folder)
file_list = list()

for file in files:

    file = os.path.join(folder, file)
    if file.endswith('.csv'):
        df = pd.read_csv(file, sep=";")
        df['filename'] = os.path.relpath(file)
        file_list.append(df)

all_days = pd.concat(file_list, axis=0, ignore_index=True, sort=False)
all_days.to_csv("/Users/user/Desktop/copy/all.csv")

我希望输出是:

A B filename
1 2 2018.12.31
3 4 2018.11.30

但实际上是:

A B filename
1 2 ../../../../Desktop/copy/2018.12.31.csv
3 4 ../../../../Desktop/copy/2018.11.30.csv

【问题讨论】:

    标签: python pandas csv directory relative-path


    【解决方案1】:

    os.path.relpath 返回相对于当前目录的文件位置。您可以使用os.path.basename(path) 获取原始文件名,或者将文件名保留为单独的变量并设置df['filename'] = file_orig

    【讨论】:

      【解决方案2】:

      如果您已经拥有.csv 文件的完整文件路径,则可以使用os.path 模块来获取文件名:

      df['filename'] = os.path.splitext(os.path.split(file)[1])[0]
      

      os.path.splitext() 将路径字符串拆分为一个以扩展名作为第二个元素的元组。 os.path.split() 将路径字符串拆分为一个以文件名(包括扩展名)为第二个元素的元组。

      如果您只使用过.csv 文件,您可以简化为:

      df['filename'] = os.path.split(file)[1][:-4]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-15
        • 2013-07-14
        • 2010-12-17
        • 1970-01-01
        • 2014-02-06
        • 1970-01-01
        • 1970-01-01
        • 2012-10-16
        相关资源
        最近更新 更多