Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the file name from a file path?

Tags:

python

I have the following code:

os.listdir("staging")

# Seperate filename from extension
sep = os.sep

# Change the casing
for n in os.listdir("staging"):
    print(n)
    if os.path.isfile("staging" + sep + n):
        filename_one, extension = os.path.splitext(n)
        os.rename("staging" + sep + n, "staging" + sep + filename_one.lower() + extension)

# Show the new file names
print ('\n--------------------------------\n')
for n in os.listdir("staging"):
    print (n)

# Remove the blanks, -, %, and /
for n in os.listdir("staging"):
    print (n)
    if os.path.isfile("staging" + sep + n):
        filename_zero, extension = os.path.splitext(n)
        os.rename("staging" + sep + n , "staging" + sep + filename_zero.replace(' ','_').replace('-','_').replace('%','pct').replace('/','_') + extension)

# Show the new file names
print ('\n--------------------------------\n')
for n in os.listdir("staging"):
    print (n)

"""
In order to fix all of the column headers and to solve the encoding issues and remove nulls, 
first read in all of the CSV's to python as dataframes, then make changes and rewrite the old files
"""
import os
import glob
import pandas as pd

files = glob.glob(os.path.join("staging" + "/*.csv"))

print(files)

# Create an empty dictionary to hold the dataframes from csvs
dict_ = {}

# Write the files into the dictionary
for file in files:
    dict_[file] = pd.read_csv(file, header = 0, dtype = str, encoding = 'cp1252').fillna('')

In the dictionary, the dataframes are named as "folder/name(csv)" what I would like to do is remove the prefix "staging/" from the keys in the dictionary.

How can I do this?

like image 392
zsad512 Avatar asked Jul 15 '17 00:07

zsad512


2 Answers

If all you want to do is truncate the file paths to just the filename, you can use os.path.basename:

for file in files:
    fname = os.path.basename(file)
    dict_[fname] = (pd.read_csv(file, header=0, dtype=str, encoding='cp1252')
                      .fillna(''))

Example:

os.path.basename('Desktop/test.txt')
# 'test.txt'
like image 193
cs95 Avatar answered Sep 28 '22 08:09

cs95


import os
pathname ='c:\\hello\\dickins\\myfile.py'
head, tail = os.path.split(pathname)
print head
print tail
like image 33
Justin Malinchak Avatar answered Sep 28 '22 08:09

Justin Malinchak