1
def readfile(file): edges = [] # to contain tuples of all edges with open(file) as f: for line in f: 

I'm trying to pass in a text file called file, then read it, but it doesn't work. Even if I cast file to a string it doesn't work. Python says

with open(file) as f: IOError: [Errno 22] invalid mode ('r') or filename: "<type 'file'>" 

How do I open a file, passed to open as a variable?

3
  • 3
    How your are calling function readfile? seems you are not passing value for file argument. Commented Feb 4, 2015 at 10:00
  • This snippet should work, please post your actual code. Commented Feb 4, 2015 at 10:03
  • first of all, rename variable file. Then, it seems that you are passing a file object to your function, and open expects a string name. So there is an inconsistency here. Commented Feb 4, 2015 at 10:04

2 Answers 2

1

Rename file by filename as file is a built-in name for python :

def readfile(filename): edges = [] # to contain tuples of all edges with open(filename) as f: for line in f: 

open() use 'r' as default mode.

Sign up to request clarification or add additional context in comments.

2 Comments

No, file is not a reserved word.
Thanks Jerome, Lafada, Kasra, georg, Marius (done), stupid mistake, not passing anything in. Doh!
1

First of all , as file is a type in python you shouldn't use it as a variable name or file name , second you need to put the file name in quote inside the open function and note that open function use read mod as default ! :

with open('file_name.txt','r') as f: for line in f: 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.