User12345
User12345

Reputation: 5480

Loop over data frame columns in pandas

I have a data frame in pandas like below.

df

, pkg
1,test_1
2,test_2
3,test_3

I have a directory that has subdirectories for each pkg in local. Each pkg subdirectory has a file called pkg.json

C:\Users\viru\Desktop\Test\pkg\pkg.json

I want to open each pkg.json file and print the contents of the file in a loop.

The for loop is below

for package in df1:
 package = 'package'
 with open('C:\Users\viru\Desktop\Test\{}\{}.json'.format(package,package)) as data_file:
   data = json.load(data_file)
   print data

I have tried like above but getting error

No such file or directory: 'C:\\Users\\viru\\Desktop\\Test\\pkg\\pkg.json'

How can I achieve what I want

Upvotes: 0

Views: 83

Answers (1)

jxramos
jxramos

Reputation: 8296

Looks like you're mistakenly iterating over the columns, so to iterate over the elements of the pkg column you should try

for pkg in df['pkg'] :
   with open('C:\Users\viru\Desktop\Test\{}\{}.json'.format(pkg,pkg)) as data_file:
       data = json.load(data_file)
       print data

Upvotes: 1

Related Questions