Arij SEDIRI
Arij SEDIRI

Reputation: 2158

How to insert strings and slashes in a path?

I'm trying to extract tar.gz files which are situated in diffent files named srm01, srm02 and srm03. The file's name must be in input (a string) to run my code. I'm trying to do something like this :

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)

I have this error message:

IOError: CRC check failed 0x182518 != 0x7a1780e1L

I want first to be sure that my code find the .tar.gz files. So I tried to just print my paths after 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

That gives :

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

The os.path.exists method tell me that my files doesn't exist.

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

That gives : False

Any way todo properly this work ? What's the best way to have first of all the right paths ?

Upvotes: 0

Views: 1590

Answers (3)

Roy Holzem
Roy Holzem

Reputation: 870

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

Never use \ with python for filepaths, \201 is \x81 character. It results to this:

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

this is why os.path.exists does not find it

Or use (r"C:\...")

I would suggest you do this:

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

Upvotes: 0

Meow
Meow

Reputation: 1267

os.path.join will create the correct paths for your filesystem

f = os.path.join('C://Users//asediri//Downloads/srm/', thirdBloc, '*.tar.gz')

Upvotes: 0

Francesco Nazzaro
Francesco Nazzaro

Reputation: 2926

In order to join paths you have to use os.path.join as follow:

import os

import tarfile
import glob

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

Upvotes: 2

Related Questions