Python 3.x 如何从目录名+;档案
在应用程序中,我可以以字符串形式获取驻留在目录中的文件的路径:Python 3.x 如何从目录名+;档案,python-3.x,string,Python 3.x,String,在应用程序中,我可以以字符串形式获取驻留在目录中的文件的路径: "/path/to/the/file.txt" 为了将另一个文件写入同一目录,我想将字符串“/path/更改为/the/file.txt”,并删除“file.txt”部分,以最终只获取 "/path/to/the/" 一串 我可以用 string = "/path/to/the/file.txt" string.split('/') 然后用一个循环将所有术语(最后一个除外)粘在一起 有简单的方法吗?您可以使用os.path.
"/path/to/the/file.txt"
为了将另一个文件写入同一目录,我想将字符串“/path/更改为/the/file.txt”
,并删除“file.txt”
部分,以最终只获取
"/path/to/the/"
一串
我可以用
string = "/path/to/the/file.txt"
string.split('/')
然后用一个循环将所有术语(最后一个除外)粘在一起
有简单的方法吗?您可以使用
os.path.basename
获取路径的最后一部分,并使用replace
将其删除
import os
path = "/path/to/the/file.txt"
delete = os.path.basename(os.path.normpath(path))
print(delete) # will return file.txt
#Remove file.txt in path
path = path.replace(delete,'')
print(path)
输出:
file.txt
/path/to/the/
假设您有一个包含txt文件的数组。你可以得到所有的路径
new_path = ['file2.txt','file3.txt','file4.txt']
for get_new_path in new_path:
print(path + get_new_path)
输出:
/path/to/the/file2.txt
/path/to/the/file3.txt
/path/to/the/file4.txt
这是我最后用的
iter = len(string.split('/'))-1
directory_path_str = ""
for i in range(0,iter):
directory_path_str = directory_path_str + srtr.split('/')[i] + "/"
感谢您对@OmerTekbiyik的评论。我对你的问题投了赞成票