Search code examples
pythonpython-2.7wxpythonipython

reading a .txt file from a folder in python script


directory =os.path.join("C:\\Users\\Desktop\\udi\\pcm-audio") 
for subdir, dirs, files in os.walk(directory): 
    for file in files: 
        if file.endswith(".txt"): 
            f=open(os.path.join(subdir, file),'r') 
            a = f.read() 
            if re.findall('\"status_code\": 0', a):
                print('Valid one') 
            else: 
                print('Invalid') 
        f.close()

I have to read only a .txt file from the folder, so I am doing as above. Later I am trying to print what I read. But I am not getting any output when I run the above program. Can someone help me what is the mistake in that ?


Solution

  • The

    f=open(os.path.join(subdir, file),'r')  
    

    that zetysz answered is right. The problem is in the start directory path you give containing backslashes.

    You can change that to forward slashes / instead of backslashes \ like this:

    directory = os.path.normpath("C:/Users/sam/Desktop/pcm-audio")
    

    or you can use double backslashes to quote them like this:

    directory = os.path.normpath("C:\\Users\sam\\Desktop\\pcm-audio")
    

    also use os.path.normpath to normalize the path. You dont need os.path.join here, since you do not join anything.

    So this should work:

    import os
    
    directory = os.path.normpath("C:/Users/sam/Desktop/pcm-audio")
    for subdir, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".txt"):
                f=open(os.path.join(subdir, file),'r')
                a = f.read()
                print a
                f.close()