Stripers247
Stripers247

Reputation: 2335

TypeError: invalid file: When trying to make a file name a variable

Hi I am trying to represent a file location as a variable because the finial script will be run on another machine. This is the code I have tried followed by the error I get. It seems to me that some how python is adding "\" and that is causing the problem. If that is the case how do I get it not to insert the "\"? Thank you

F = 'C:\Documents and Settings\myfile.txt','r'
f = open(F)

and the error

TypeError: invalid file: ('C:\\Documents and Settings\\myfile.txt', 'r')

Upvotes: 2

Views: 25772

Answers (3)

quinao
quinao

Reputation: 79

Instead of writing / or \, you should do this:

import os
F = os.path.join(
    "C:",
    os.path.join(
        "Documents and Settings", "myfile.txt"
    )
)
f = open(F, 'r')`

so that it uses / or \ according to your os.

(Although if you write C:/ it must mean you want to run your code on Windows... Hum...)

Upvotes: 1

moesef
moesef

Reputation: 4841

Try

f=open('C:\Documents and Settings\myfile.txt','r')

Instead of using the variable F. the way you have it 'r' is part of the file name, which it is not.

Upvotes: 3

icyrock.com
icyrock.com

Reputation: 28608

From the docs:

Try this:

F = r'C:\Documents and Settings\myfile.txt'
f = open(F, 'r')

About the "double backslashes" - you need to escape backslashes in your strings or use r'string', see this:

E.g. try this:

>>> a = 'a\nb'
>>> print a
a
b

To get what you expect, you need this:

>>> a = r'a\nb'
>>> print a
a\nb

or this:

>>> a = 'a\\nb'
>>> print a
a\nb

Upvotes: 5

Related Questions