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

时间:2015-07-08 01:40:54

标签: 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 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()

我的问题: 我想用触摸屏在raspberry pi(python 2.7)上运行此代码。我想尽量避免打字。

问题:

用户使用下面的代码选择他想要阅读的文件。 这会创建一个类似于这样的变量:“C:/Users/Andrew/Desktop/Python/LOG1.txt”(注意:我意识到这是一个windows文件路径,在pi上它会创建一个linux文件路径)

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

然后我将用户输入新文件名并将文件保存到某个目录。

#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中取出文件路径的“LOG1”部分。所以基本上我删除了变量的“C:/ Users / Andrew / Desktop / Python /”和“.txt”部分,但保留了文件的名称。然后我想把这个文件名称为“LOG1”,并将其用于我上面定义的completeName变量。我会使用代码:

completeName = os.path.join(save_path,**INSERT VARIABLE HERE**, +".csv")

这会创建一个名为“LOG1.csv”的csv文件

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

4 个答案:

答案 0 :(得分:3)

也许os.path.basename()os.path.splitext()可以解决您的问题

答案 1 :(得分:2)

您可以使用os.path.splitos.path.splitext

filename = "C:/Users/Andrew/Desktop/Python/LOG1.txt"

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

'LOG1'

答案 2 :(得分:1)

如果你是python 3.4,你可以使用pathlib来处理路径。例如:

import pathlib

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

a_path = pathlib.Path(save_path)

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

答案 3 :(得分:0)

这样的事情很快就会做到:

name = '{0}.csv'.format(filename1.split('/')[-1].split('.')[0])
completeName = os.path.join(save_path, name)