0

I'm new to coding and have started to try out the OS module, it occasionally it will work on specific paths. example:

but when I try to interact with an individual file this will happen:

print(os.stat('my_file.txt'))

>>>filenotfounderror: [errno 2] no such file or directory found. 
'my_file.txt'

or when I try to interact with a path that is not in my cwd then this would happen:

print(os.listdir(C:\folder\folder\folder))

>>>SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in 
position 2-3: truncated \UXXXXXXXX escape

I don't understand why this is happening and it would be great if someone could explain why this is happening, thanks.

2
  • You don't have quotes around C:\folder\folder\folder Commented Dec 17, 2018 at 9:05
  • whoops, i just missed that when writing the question but this was not in the script. thanks anyway Commented Dec 17, 2018 at 10:49

1 Answer 1

1

Python tells your that my_file.txt does not exist in the current directory in your first example.

Verify that you have a file called my_file.txt and then check the current working directory of your python process with os.getcwd().

For your second example, in python the backslash \ is a special character for escape sequences in a string. For example the linefeed \n or the tab \t.

The error in your example is most likely the result of accidentaly forming an invalid escape sequence by not escaping the backslash itself like this:

print(os.listdir('C:\\folder\\folder\\folder'))
Sign up to request clarification or add additional context in comments.

2 Comments

my_file.txt is just an example file just as \folder\folder\folder is. but yes i do have the correct file name in my script. ahhhhh so i have to change my cwd using os.chdir and then i can access the file within that directory. the double back slash also worked. thanks allot for the help
@BOBTHEBUILDER Or you can use the full path of my_file.txt instead of changing directory.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.