Python 如何从文件路径中提取文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45113157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:41:35  来源:igfitidea点击:

How to extract the file name from a file path?

python

提问by zsad512

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.

在字典中,数据帧被命名为“文件夹/名称(csv)”我想要做的是从字典中的键中删除前缀“staging/”。

How can I do this?

我怎样才能做到这一点?

采纳答案by cs95

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

如果您只想将文件路径截断为文件名,则可以使用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'

回答by JerryPlayz101

As ColdSpeed said, you can use "os.path.basename" to truncate a file to its name, but I think what you are refering to is the ability to pycache the data?

正如 ColdSpeed 所说,您可以使用“os.path.basename”将文件截断为其名称,但我认为您所指的是 pycache 数据的能力?

For Example here is my Directory: My Directory for the Game I'm Making AtmIn the Assets folder..

例如这里是我的目录: 我正在制作 Atm 的游戏目录在资产文件夹中..

You see the pycachefolder? that initializes it as a module. Then, you can import a file from that module (for example the staging.txt file and operate on it.) For ExampleI use the IpConfig.txt File from the assets folder level (or should be) and take a line of information out of it.

你看到pycache文件夹了吗?将其初始化为模块。然后,您可以从该模块导入一个文件(例如 staging.txt 文件并对其进行操作。) 例如我使用资产文件夹级别(或应该是)的 IpConfig.txt 文件并从中取出一行信息.

import pygame as pyg
import sys
import os
import math
import ssl
import socket as sock
import ipaddress as ipad
import threading
import random
print("Modules Installed!")

class two:
    # Find out how to refer to class super construct
    def main(Display, SecSock, ipadd, clock):
        # I have code here that has nothing to do with the question...


    def __init__():
        print("Initializing[2]...")
        # Initialization of Pygame and SSL Socket goes here

        searchQuery = open("IpConfig.txt", 'r') #Opening the File IpConfig(Which now should open on the top level of the game files)

        step2 = searchQuery.readlines()# read the file
        ipadd = step2[6] # This is what you should have or something similar where you reference the line you want to copy or manipulate.

        main(gameDisplay, SSLSock, ipadd, clock)# Im having issues here myself - (main() is not defined it says)
        print(ipadd)
        print("Server Certificate Configuration Enabled...")








    __init__() # Start up the procedure

回答by Santhosh

This articlehere worked out just fine for me

这篇文章对我来说很好

import os
inputFilepath = 'path/to/file/foobar.txt'
filename_w_ext = os.path.basename(inputFilepath)
filename, file_extension = os.path.splitext(filename_w_ext)
#filename = foobar
#file_extension = .txt

path, filename = os.path.split(path/to/file/foobar.txt)
# path = path/to/file
# filename = foobar.txt

Hope it helps someone searching for this answer

希望它可以帮助寻找这个答案的人

回答by Justin Malinchak

import os
pathname ='c:\hello\dickins\myfile.py'
head, tail = os.path.split(pathname)
print head
print tail