我有以下代碼:如何從文件路徑中提取文件名?
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('')
在詞典中,dataframes被命名爲「文件夾/名稱(CSV)」我希望做的是從鍵刪除前綴「分期/」詞典。
我該怎麼做?
@COLDSPEED,我不知道如何執行你的suggestion-我有61鍵在字典中,他們被標記爲「staging /文件名」我想將鍵改爲「文件名」 - 我試着用files = glob.glob(os.path.join(「staging」+「/ * .csv「)) print(files) 對於文件中的文件: file = os.path.basename(file) print(files) – zsad512
請看如何提供[mcve]。 –