0

I'm trying to read the first 20 characters of several files that I have in a folder using the code shown below:

import os
path = raw_input("Enter the path: ")
listing = sorted(os.listdir(path))
for infile in listing:
    print "current file is: " + infile
    with open(infile) as fl: # Use fl to refer to the file object
        #print infile
        data = fl.read(20)
        print data
        fl.close()

But I'm getting this error:

Enter the path: /home/david/dat_files_new

current file is: raw_57_0000.dat
# == pyFAI calibrati
current file is: raw_57_0001.dat

---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-53-7292764186b6> in <module>()
      7 for infile in listing:
      8     print "current file is: " + infile
----> 9     with open(infile) as fl: # Use fl to refer to the file object
     10         #print infile
     11         data = fl.read(20)

IOError: [Errno 2] No such file or directory: 'raw_CL20_57_0001.dat'

I can list all the files in the directory if I comment the with statement and everything that it is below.

This is what the code does:

  • Sort the files within a directory --> done

  • Print name of first file --> done

  • Read the first 20 characters of the first file --> done

  • Print name of seconde file --> done

  • Read the first 20 characters of the second file --> failed

  • Read the first 20 characters of the second file

Maxwell's Daemon
  • 587
  • 1
  • 6
  • 21

0 Answers0