0

I want to read multiple text files in the folder. I am using os.listdir() to get every file in my folder. I'm using open to read the text file and write to write the file. However, an error comes out when I run the code. Here I attached the code.

import os
infilename = os.listdir("C:\Python27\input") 
for filename in infilename:
    f = open(filename, "r")
    data = f.read()
    f.close()
j.j
  • 9
  • 3
  • Where do you put your script and how do you run it? You might have the wrong relative path – dazedconfused Jun 16 '16 at 01:45
  • I put the script inside of Python folder. I run using Python Shell. When I print filename, It shows the name of my files but can't read it. like this, – j.j Jun 16 '16 at 01:50
  • for filename in infilename: print filename satu.txt satu2.txt – j.j Jun 16 '16 at 01:50

4 Answers4

2

Unless your python script is in the same directory, you will get this error.

You need to reference the full path to the file, not just the file name.

import os

indir = "C:\Python27\input"

for filename in os.listdir(indir):
    fullpath = os.path.join(indir,filename)
    with open(fullpath, "r") as f:
        data = f.read()
Nick
  • 7,103
  • 2
  • 21
  • 43
0

The problem here is that os.listdir only returns the files in that directory, only the names. You must add the path in front of the file name for it to work.

import os
import sys

drive = os.path.splitdrive(sys.executable)[0]
drive = os.path.join(drive, "Python27")
drive = os.path.join(drive, "input")
infilename = os.listdir(drive)
for filename in infilename:
    f = open(os.path.join(drive, filename), "r")
    data = f.read()
    f.close()
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38
0

os.listdir will return just the filenames, you need to combine the file name, with the directory name in order for open to find it:

import os

infilename = os.listdir(r'C:\Python27\input')
for filename in infilename:
    f = open(os.path.join(r'C:\Python27\input', filename), 'r')
    data = f.read()
    f.close()

If you are using \ in a string, you should use raw strings, so characters such as \n are taken literally and not interpreted; the r' at the beginning of the string marks it as a raw string (so Python takes it literally).

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • I already can read and write all files inside the folder using this code.May I know, why the result saves only one file. It replaces an old one with a new file. – j.j Jun 16 '16 at 03:40
0
import os
path = "C:\\Python27\\input"
infilename = os.listdir(path) 
for filename in infilename:
    print(path + "\\"+ filename)
    f = open(path + "\\" + filename, "r")
    data = f.read()
    f.close()
zondo
  • 19,901
  • 8
  • 44
  • 83
Robert Columbia
  • 6,313
  • 15
  • 32
  • 40