Mark K
Mark K

Reputation: 9338

Python reading files in different local drive locations

Could someone shed me some lights on the file path matter in Python?

For example my codes need to read a batch of files, the file names are listed and stored in a .txt file, C:\filelist.txt, which content is:

C:\1stfile.txt
C:\2ndfile.txt
C:\3rdfile.txt
C:\4thfile.txt
C:\5thfile.txt

And the codes start with:

list_open = open('c:\\aaa.txt')
read_list = list_open.read()
line_in_list = read_list.split('\n')

all run fine. But if I want to read files in another path, such as:

C:\WorkingFolder\6thfile.txt
C:\WorkingFolder\7thfile.txt
C:\WorkingFolder\8thfile.txt
C:\WorkingFolder\9thfile.txt
C:\WorkingFolder\10thfile.txt

It doesn’t work. I guess the path here C:\WorkingFolder\ is not properly put so Python cannot recognize it.

So in what way I shall put it? Thanks.




hello all,

sorry that maybe i didn't make my self clear.

the problem is, a text file, c:\aaa.txt contains below:

C:\1stfile.txt
C:\WorkingFolder\1stfile.txt

why only C:\1stfile.txt is readable, but the other one not?

Upvotes: 1

Views: 26431

Answers (3)

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

import os

BASEDIR = "c:\\WorkingFolder"

list_open = open(os.path.join(BASEDIR, 'aaa.txt'))

Upvotes: 2

camleng
camleng

Reputation: 1028

Simply try using forward slashes instead.

list_open = open("C:/WorkingFolder/6thfile.txt", "rt")

It works for me.

Upvotes: 1

jrd1
jrd1

Reputation: 10716

The reason your program isn't working is that you're not changing the directory properly. Use os.chdir() to do so, then open the files as normal:

import os

path = "C:\\WorkingFolder\\"

# Check current working directory.
retval = os.getcwd()

print "Current working directory %s" % retval

# Now change the directory
os.chdir( path )

# Check current working directory.
retval = os.getcwd()

print "Directory changed successfully %s" % retval

REFERENCES: http://www.tutorialspoint.com/python/os_chdir.htm

Upvotes: 3

Related Questions