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

如何在python中从文件路径提取文件名?,python,csv,filepath,Python,Csv,Filepath,课程概述: 我的程序将导入用户使用文件浏览器选择的数据文件。然后,我解包二进制文件。然后,我将新解包的数据保存为.csv文件,以便以后在excel中查看数据。用户当前通过键入新文件名来创建文件名。然后,我继续使用matplotlib库绘制所有数据 整个代码: #import Gnuplot import struct #import binascii import csv import matplotlib.pyplot as plt import os.path import pylab as

课程概述:

我的程序将导入用户使用文件浏览器选择的数据文件。然后,我解包二进制文件。然后,我将新解包的数据保存为.csv文件,以便以后在excel中查看数据。用户当前通过键入新文件名来创建文件名。然后,我继续使用matplotlib库绘制所有数据

整个代码:

#import Gnuplot
import struct
#import binascii
import csv
import matplotlib.pyplot as plt
import os.path
import pylab as pl
from Tkinter import Tk
from tkFileDialog import askopenfilename

#print "testing" 
#data = '$'
#data2 = '7'

#out = ord(data)*256 + ord(data2)
#print out


'''
open_path = "/media/6265-D02D/"

fname = raw_input('Enter the file name you want to open (without the entire filepath)(include filetype ex. .txt): ')
#combines open_path with fname
entirepath = os.path.join(open_path, fname)

f = open(entirepath, 'r')
'''

#This opens the file browser inorder to the user to
#choose the file that they want to decipher
Tk().withdraw() '''we don't want a full GUI, so keep the root
window from appearing.
-This opens the filebrowser'''
filename1 = askopenfilename()
f = open(filename1 'r')





time = []
pitch = []
roll = []
yaw = []
p_rate = []
r_rate = []
y_rate = []
motor0 = []
motor1 = []
motor2 = []
motor3 = []
alt = []
thr_in = []
pitch_in = []
roll_in = []
yaw_in = []

byte_count = 50

s = struct.Struct('>3s I h h h h h h h h h h I h h h h s')
while True:
    temp_data = []
    unpacked_date = [] 
    temp_data = f.read(40)
    byte_count = len(temp_data)
    if byte_count <40:
        break

    unpacked_data = s.unpack(temp_data)

    if unpacked_data[0] == '$$$': #storing the unpacked data if a good packet is received
        time.append(unpacked_data[1])
        pitch.append(unpacked_data[2])
        roll.append(unpacked_data[3])
        yaw.append(unpacked_data[4])
        p_rate.append(unpacked_data[5])
        r_rate.append(unpacked_data[6])
        y_rate.append(unpacked_data[7])
        motor0.append(unpacked_data[8])
        motor1.append(unpacked_data[9])
        motor2.append(unpacked_data[10])
        motor3.append(unpacked_data[11])
        alt.append(unpacked_data[12])
        thr_in.append(unpacked_data[13])
        yaw_in.append(unpacked_data[14])
        pitch_in.append(unpacked_data[15])
        roll_in.append(unpacked_data[16])


#code not being used here
# Create plot from interpreted data
#pitch_plot = Gnuplot.Gnuplot()
#pitch_plot.title('Pitch vs. Time')
#pitch_plot('set style data linespoints')
#pitch_plot(time, pitch)







#creating a new csv file using the new parsed data

creatingcolumns = (time,pitch,roll,yaw, p_rate,
r_rate,y_rate,motor0,motor1,motor2,motor3,alt,
thr_in,yaw_in,pitch_in,roll_in)
creatingcolumns = zip(*creatingcolumns)

#creates headers
header = ["Time", "Pitch", "Roll", "Yaw", "P Rate",
"R Rate", "Y Rate", "Motor 0", "Motor 1", "Motor 2",
"Motor 3", "Altitude", "Thrust In", "Yaw In",
"Pitch in", "Roll in"]

#saves the file to the python, csv folder on the desktop
#determines the save path
save_path = "/home/pi/Desktop/Python CSV files"
#user inputs a file name
filename2 = raw_input("Give a name for the new CSV file (do not include the filetype such as .csv) ")
#combining everything into a variable for the save path
completeName = os.path.join(save_path, filename2+".csv")

#opens a new csvfile and writes the information to it
with open(completeName , "wb" ) as csvfile:
        writingcsv = csv.writer(csvfile, dialect='excel')
        writingcsv.writerow(header)
        for row in creatingcolumns:
            writingcsv.writerow(row)








#plots the data and creates the titles
#creates the first figure of Time vs Pitch
plt.figure(1)
plt.plot(time,pitch)
plt.xlabel('Time')
plt.ylabel('Pitch')
plt.title('Pitch vs Time')
fig = pl.gcf()
fig.canvas.set_window_title('Pitch vs Time')
#plt.show()

#creates second figure of Time vs Roll
plt.figure(2)
plt.plot(time, roll)
plt.title('Roll vs Time')
plt.xlabel('Time')
plt.ylabel('Roll')
fig2 = pl.gcf()
fig2.canvas.set_window_title('Roll vs Time')

#creates second figure of Time vs Yaw
plt.figure(3)
plt.plot(time, yaw)
plt.title('Yaw vs Time')
plt.xlabel('Time')
plt.ylabel('Yaw')
fig3 = pl.gcf()
fig3.canvas.set_window_title('Yaw vs Time')

#creates second figure of Time vs Pitch Rate
plt.figure(4)
plt.plot(time, p_rate)
plt.title('Pitch Rate vs Time')
plt.xlabel('Time')
plt.ylabel('Pitch Rate')
fig4 = pl.gcf()
fig4.canvas.set_window_title('Pitch Rate vs Time')

#creates second figure of Time vs Roll Rate
plt.figure(5)
plt.plot(time, r_rate)
plt.title('Roll Rate vs Time')
plt.xlabel('Time')
plt.ylabel('Roll Rate')
fig5 = pl.gcf()
fig5.canvas.set_window_title('Roll Rate vs Time')

#creates second figure of Time vs Yaw Rate
plt.figure(6)
plt.plot(time, y_rate)
plt.title('Yaw Rate vs Time')
plt.xlabel('Time')
plt.ylabel('Yaw Rate')
fig6 = pl.gcf()
fig6.canvas.set_window_title('Yaw Rate vs Time')

#creates second figure of Time vs Motor 0
plt.figure(7)
plt.plot(time, yaw)
plt.title('Motor 0 vs Time')
plt.xlabel('Time')
plt.ylabel('Motor 0')
fig7 = pl.gcf()
fig7.canvas.set_window_title('Motor 0 vs Time')

#creates second figure of Time vs Motor 1
plt.figure(8)
plt.plot(time, motor1)
plt.title('Motor 1 vs Time')
plt.xlabel('Time')
plt.ylabel('Motor 1')
fig8 = pl.gcf()
fig8.canvas.set_window_title('Motor 1 vs Time')

#creates second figure of Time vs Motor 2
plt.figure(9)
plt.plot(time, motor2)
plt.title('Motor 2 vs Time')
plt.xlabel('Time')
plt.ylabel('Motor 2')
fig9 = pl.gcf()
fig9.canvas.set_window_title('Motor 2 vs Time')

#creates second figure of Time vs Motor 3
plt.figure(10)
plt.plot(time, motor3)
plt.title('Motor 3 vs Time')
plt.xlabel('Time')
plt.ylabel('Motor 3')
fig10 = pl.gcf()
fig10.canvas.set_window_title('Motor 3 vs Time')

#creates second figure of Time vs Altitude
plt.figure(11)
plt.plot(time, alt)
plt.title('Altitude vs Time')
plt.xlabel('Time')
plt.ylabel('Altitude')
fig11 = pl.gcf()
fig11.canvas.set_window_title('Altitude vs Time')

#creates second figure of Time vs Thrust in 
plt.figure(12)
plt.plot(time, thr_in)
plt.title('Thrust In vs Time')
plt.xlabel('Time')
plt.ylabel('Thrust In')
fig12 = pl.gcf()
fig12.canvas.set_window_title('Thrust In vs Time')

#creates second figure of Time vs Yaw Input
plt.figure(13)
plt.plot(time, yaw_in)
plt.title('Yaw Input vs Time')
plt.xlabel('Time')
plt.ylabel('Yaw Input')
fig13 = pl.gcf()
fig13.canvas.set_window_title('Yaw Input vs Time')

#creates second figure of Time vs Pitch Input
plt.figure(14)
plt.plot(time, pitch_in)
plt.title('Pitch Input vs Time')
plt.xlabel('Time')
plt.ylabel('Pitch Input')
fig14 = pl.gcf()
fig14.canvas.set_window_title('Pitch Input vs Time')

#creates second figure of Time vs Roll Input
plt.figure(15)
plt.plot(time, roll_in)
plt.title('Roll Input vs Time')
plt.xlabel('Time')
plt.ylabel('Roll Input')
fig15 = pl.gcf()
fig15.canvas.set_window_title('Roll Input vs Time')
plt.show()
然后,我让用户输入新的文件名,并将文件保存到某个目录中

#saves the file to the python, csv folder on the desktop
#determines the save path
save_path = "/home/pi/Desktop/Python CSV files"
#user inputs a file name
filename2 = raw_input("Give a name for the new CSV file (do not include the filetype such as .csv) ")
#combining everything into a variable for the save path
completeName = os.path.join(save_path, filename2+".csv")
我想从变量filename1中去掉filepath的“LOG1”部分。因此,基本上我删除了变量的“C:/Users/Andrew/Desktop/Python/”和“.txt”部分,但保留了文件名。然后,我希望将此文件名“LOG1”用于上面定义的completeName变量。我将使用以下代码:

completeName = os.path.join(save_path,**INSERT VARIABLE HERE**, +".csv")
这将创建一个名为“LOG1.csv”的csv文件

如何删除文件路径的无关部分??
谢谢

也许或者可以解决你的问题

像这样的事情会很快解决:

name = '{0}.csv'.format(filename1.split('/')[-1].split('.')[0])
completeName = os.path.join(save_path, name)
您可以使用和:


如果您使用的是python 3.4,那么您可以使用它来处理路径。例如:

import pathlib

save_path = "/home/pi/Desktop/Python CSV files"

a_path = pathlib.Path(save_path)

print(a_path.name) # gives: Python CSV files

非常感谢!!非常感谢你的帮助!
filename = "C:/Users/Andrew/Desktop/Python/LOG1.txt"

os.path.splitext(os.path.split(filename)[1])[0]

'LOG1'
import pathlib

save_path = "/home/pi/Desktop/Python CSV files"

a_path = pathlib.Path(save_path)

print(a_path.name) # gives: Python CSV files