20

I am very new to programming and the python language.

I know how to open a file in python, but the question is how can I open the file as a parameter of a function?

example:

function(parameter)

Here is how I have written out the code:

def function(file):
    with open('file.txt', 'r') as f:
        contents = f.readlines()
    lines = []
    for line in f:
        lines.append(line)
    print(contents)    
ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
user2891763
  • 373
  • 3
  • 6
  • 12
  • Not so clear. What do you want to do with it? do you want to pass the file object, the content or what? Hurry up or you're gonna get downvoted. – aIKid Oct 22 '13 at 04:00
  • oh I want to read the file – user2891763 Oct 22 '13 at 04:01
  • You mean you want to pass the file content, as a parameter? – aIKid Oct 22 '13 at 04:01
  • the python should return the contents of the file as a list – user2891763 Oct 22 '13 at 04:01
  • yeahs that is what I want – user2891763 Oct 22 '13 at 04:02
  • You need to pass the content of a file to a function, which will return a list of the lines. Am i correct? – aIKid Oct 22 '13 at 04:02
  • Side-note: The `readlines` method on files is redundant with files iterator behavior; in Python 3, `f.readlines()` is more verbose and no faster than (and in fact, in my tests, fractionally slower than) `list(f)`, and makes people write bad code by obscuring the iterator nature of files. In reality, you rarely want to do either `f.readlines()` or `list(f)`, because you usually want to iterate the file directly, either to process lines one at a time and discard them, or if you need a `list`, you still want some preprocessing (e.g. stripping newlines and/or blank lines) that as you iterate. – ShadowRanger Jun 15 '16 at 15:06

5 Answers5

21

You can easily pass the file object.

with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable.

and in your function, return the list of lines

def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines 

Another trick, python file objects actually have a method to read the lines of the file. Like this:

with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).

With the second method, readlines is like your function. You don't have to call it again.

Update Here is how you should write your code:

First method:

def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines 
with open('file.txt', 'r') as f: #open the file
    contents = function(f) #put the lines to a variable (list).
    print(contents)

Second one:

with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).
    print(contents)

Hope this helps!

aIKid
  • 24,039
  • 4
  • 38
  • 65
  • what does this mean: SyntaxError: 'return' outside function – user2891763 Oct 22 '13 at 04:15
  • Whoops, sorry. Fixed it now. Wrong indentation. – aIKid Oct 22 '13 at 04:16
  • now it says : builtins.NameError: name 'function' is not defined – user2891763 Oct 22 '13 at 04:18
  • 2
    Define the function first, then execute the `with` statement. – aIKid Oct 22 '13 at 04:18
  • 1
    nice but why to reinvent?, you can readlines simply as f.readlines() or f.read() and if you want the list then you can use the split – DevC Oct 22 '13 at 04:19
  • @DevC Yup, i know that very well. I just want him to see the logic. – aIKid Oct 22 '13 at 04:20
  • okay so now there arnt any errors, when I compile it. So in the Python Shell what command should I use in order to run this function – user2891763 Oct 22 '13 at 04:22
  • If you use the code in my `with` statement, it should already run. Try printing the `contents` variable at the end of the file. – aIKid Oct 22 '13 at 04:25
  • i don't know it still doesn't seem to be printing.... Sorry if I am bugging you too much but I am a real new at this programming business. – user2891763 Oct 22 '13 at 04:29
  • Are you trying this on the interactive interpreter? – aIKid Oct 22 '13 at 04:33
  • I am using the IDE called Wing – user2891763 Oct 22 '13 at 04:34
  • Try this in your python shell tab. – aIKid Oct 22 '13 at 04:41
  • I will update my question and show you how I have written out your code – user2891763 Oct 22 '13 at 04:43
  • Updated my answer. Try it. – aIKid Oct 22 '13 at 04:51
  • Wow thanks !!! I am on the verge of tearing my hair off of my head.. for not getting such simple logic. Thank you very much ! – user2891763 Oct 22 '13 at 04:56
  • Why is the example opening the file outside the function? Seems like the function was intended to receive a file name, open and read it, and return the contents as a `list`. Moving the `open` outside the function may make it more flexible (it can now be passed arbitrary file-like objects opened in different ways), but if the function is _supposed_ to open the file the same way, it just means all callers are doing the same work, when they could just pass the file name and keep the common file open code in the function. – ShadowRanger Jun 15 '16 at 14:53
  • I suppose it's possible the OP wanted to open the file outside the function and pass the file object, not the name, but that's really unclear from question and comments. – ShadowRanger Jun 15 '16 at 14:54
0

Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)

0
def fun(file):
    contents = None

    with open(file, 'r') as fp:
        contents = fp.readlines()

    ## if you want to eliminate all blank lines uncomment the next line
    #contents = [line for line in ''.join(contents).splitlines() if line]

    return contents

print fun('test_file.txt')

or you can even modify this, such a way it takes file object as a function arguement as well

Siva Cn
  • 909
  • 4
  • 10
  • If you're going to do `splitlines` to remove newlines from lines and/or blank line elimination, you're better off either slurping as a single value and splitting, or processing line by line. Reading all the lines to a `list`, `join`ing the `list`, then `split`ing it up again is wasted work/memory (you're storing three copies of file data at once). – ShadowRanger Jun 15 '16 at 14:24
  • For a list of lines without newlines, you'd minimize time (if you have sufficient memory) with `contents = f.read().splitlines()` (which drops peak memory one copy of file data as a block and two copies of `list` of lines to one of each), or without blank lines (and still only two copies in memory at once), `contents = list(filter(None, f.read().splitlines()))`. To only have one copy as a `list`, no complete copies of the data in memory, process it line by line and both strip and filter as you go: `contents = [x for x in (x.rstrip('\r\n') for x in f) if x]` – ShadowRanger Jun 15 '16 at 14:43
  • Oh, and just for completeness, if you want to strip all trailing whitespace (not just newlines) and then strip blank lines, it can be optimized to `contents = list(filter(None, map(str.rstrip, f)))` which moves all the work to the C layer in CPython, at the expense of using `map` and `filter`, generally considered less Pythonic. Stripping only newlines is also possible this way, it's just uglier: `from operator import methodcaller`, `contents = list(filter(None, map(methodcaller('strip', '\r\n'), f)))` – ShadowRanger Jun 15 '16 at 14:45
0

Here's a much simpler way of opening a file without defining your own function in Python 3.4:

var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file

Here are the types of files:

  • "r": just to read a file

  • "w": just to write a file

  • "r+": a special type which allows both reading and writing of the file

For more information see this cheatsheet.

Tim Diekmann
  • 6,764
  • 10
  • 34
  • 58
G.Bhalla
  • 35
  • 6
-2
def main():
       file=open("chirag.txt","r")
       for n in file:
              print (n.strip("t"))
       file.close()
if __name__== "__main__":
       main()


the other method is 


with open("chirag.txt","r") as f:
       for n in f:
              print(n)
John Don
  • 97
  • 1
  • 2
  • 12
  • 2
    This adds nothing to the existing answers, the formatting is terrible, and using explicit `close` instead of implicit close via `with` as your primary example is just encouraging bad practices. – ShadowRanger Jun 15 '16 at 14:18