Opening Files in Python - Newbie Question

  • Context: Python 
  • Thread starter Thread starter zeion
  • Start date Start date
  • Tags Tags
    Python
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
zeion
Messages
455
Reaction score
1

Homework Statement



Hi, this might be silly but I'm not sure what the syntax is for the read function...

I'm trying to open a file on my desktop, it is a text file called testfile.txt, how do I make python know where to find it?

I go:

f = open('C:\Users\Truman\Desktop\testfile.txt', 'r')

or

f = open('testfile.txt', 'r')

but neither works.

Does the file need to be in the same directory as where I installed Python?

Thanks.

Homework Equations





The Attempt at a Solution

 
Physics news on Phys.org
Code:
f = open(filename, mode)
should work if you specify the file path.

Are you getting an IOError? Also, if you directly use the file() constructor, can you open the file?
 
Ok I realized I couldn't open the file in IDLE.. but only with the actual program.
 
Either use double backslashes, '\\', or single forward slashes, '/'. Otherwise you have characters like '\t', which is the tab character, embedded in your filename.
 
Wow...it's been so long since I've used Python on Windows that I forgot about that.