如何在路径中插入字符串和斜杠?

时间:2016-09-07 13:17:04

标签: python python-2.7 filepath glob tarfile

我试图提取位于名为srm01,srm02和srm03的不同文件中的tar.gz文件。 文件的名称必须是输入(字符串)才能运行我的代码。 我试图做这样的事情:

import tarfile
import glob

thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob.glob('C://Users//asediri//Downloads/srm/'+thirdBloc+'/'+'*.tar.gz'):
    tar = tarfile.open(f)
    tar.extractall('C://Users//asediri//Downloads/srm/'+thirdBloc)

我有以下错误消息:

IOError: CRC check failed 0x182518 != 0x7a1780e1L

我首先要确保我的代码找到.tar.gz文件。所以我试着在glob之后打印我的路径:

thirdBloc = 'srm01' #Then, that must be 'srm02', or 'srm03'
for f in glob.glob('C://Users//asediri//Downloads/srm/'+thirdBloc+'/'+'*.tar.gz'):
    print f

这给出了:

C://Users//asediri//Downloads/srm/srm01\20160707000001-server.log.1.tar.gz
C://Users//asediri//Downloads/srm/srm01\20160707003501-server.log.1.tar.gz

os.path.exists方法告诉我我的文件不存在。

print os.path.exists('C://Users//asediri//Downloads/srm/srm01\20160707000001-server.log.1.tar.gz')

这给出了:错误

以任何方式妥善完成这项工作?首先拥有正确路径的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

要加入路径,您必须使用os.path.join,如下所示:

require 'uri' # probably not necessary if you are using Rails

old_url  = "/bookings/hotels//Pune?arrival_date=blahblah"
uri      = URI(old_url)

# remove everything between the first double '//' and the end of the string
uri.path = uri.path.gsub(/\/\/.+\Z/, '')
# => "/bookings/hotels"

# output a new url using the new path but including the original query string
new_url  = uri.to_s
# =>  "/bookings/hotels?arrival_date=blahblah"

答案 1 :(得分:0)

os.path.join将为您的文件系统

创建正确的路径
f = os.path.join('C://Users//asediri//Downloads/srm/', thirdBloc, '*.tar.gz')

答案 2 :(得分:0)

C://Users//asediri//Downloads/srm/srm01\20160707000001-server.log.1.tar.gz

永远不要使用\ python执行文件路径,\ 201是\ x81字符。结果如下:

C://Users//asediri//Downloads/srm/srm01ü60707000001-server.log.1.tar.gz

这就是为什么os.path.exists找不到它

或使用(r"C:\...")

我建议你这样做:

import os
os.chdir("C:/Users/asediri/Downloads/srm/srm01")
for f in glob.glob(str(thirdBloc) + ".tar.gz"):
    print f