0

For my project, I read a line of input from my text file that reads "D C:/Test/Project1". The D signifies to print the files in the directory, ignoring subdirectories. "R" signifies to print the files in the directory and every subdirectory. The specific directory follows the letter after a space. The directory contains a few python files.

import os
from pathlib import Path

infile = open("input.txt", "r")


def subfolder(p):
    contents = p.iterdir()
    for i in contents:
        if i.is_file(): 
            print(i)
        elif i.is_dir():
            subfolder(i)        

for line in infile:
    if line[0] == "R":
        p = Path(str(line[2:]))
        contents = p.iterdir()
        for i in contents:
            print(i)
            if i.is_file():
                print(i)
            elif i.is_dir():
                subfolder(i)
    elif line[0] == "D":
         p = Path(str(line[2:]))
         contents = p.iterdir()
         for i in contents:
             print(i)
             if i.is_file():
                 print(i)
    else:
         print("ERROR")

infile.close()

When I run this code, I receive the error message

Traceback (most recent call last):
  File "C:\Users\jmelu\AppData\Local\Programs\Python\Python36-32\Project 1.py", line 32, in <module>
    for i in contents:
  File "C:\Users\jmelu\AppData\Local\Programs\Python\Python36-32\lib\pathlib.py", line 1059, in iterdir
    for name in self._accessor.listdir(self):
  File "C:\Users\jmelu\AppData\Local\Programs\Python\Python36-32\lib\pathlib.py", line 387, in wrapped
    return strfunc(str(pathobj), *args)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Test\\Project1\n'

Previously, this same exact code worked earlier and it works on other computers as well. I tried reinstalling pathlib but to no success. I am on python 3.6.2.

2
  • You didn't take the line breaks off. Oct 19, 2018 at 2:03
  • Sorry what do you mean by line breaks? I'm new to this and don't understand. Oct 19, 2018 at 2:11

1 Answer 1

1

You're reading your paths from a file with a path per line, but you didn't strip the newlines from each string, so you're looking for files that include a newline character, \n. As your error message notes, the invalid path was:

'C:\\Test\\Project1\n' <-- Single slash followed by n; directories are double slash separated

Strip them off as you read, and you'll be fine:

for line in infile:
    line = line.rstrip("\r\n")  # Removes all trailing carriage returns and newlines
    if line[0] == "R":
1
  • Thanks! I forgot that I had a blank line in my text file that I didn't even consider in my input. Oct 19, 2018 at 4:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.