Kifsif
Kifsif

Reputation: 3843

Python 3: working with files

I'm reading in my textbook that a file object has a readlines method, which loads a whole file into a list of strings:

>>> f = open('script1.py')
>>> lines = f.readlines()
>>> lines

Result:

['import sys\n', 'print(sys path)\n', 'x = 2\n', 'print(2**33)\n']

I always like to consult a documentation when I analyse what I read. But I met my Waterloo trying to find this in the documentation? Could you help me?

Upvotes: 0

Views: 986

Answers (3)

TerrenceHu
TerrenceHu

Reputation: 11

help(f) or just help(f.readlines) will help you. However, readlines() is almost deprecated and not recommended, especially when the file is of large size.

If you want to iterate over the file, you can use:

for line in f: process(line)

If you want to handle the whole file, just use:

all_the_text = open('script1.py').read()

Upvotes: 1

jfs
jfs

Reputation: 414235

The docs for open() describe what values and under what conditions it may return with links to their documentation. In particular .readlines() method is described in the docs for common base class io.IOBase.

I use google or the search field in the docs or help(f.readlines) (or an equivalent such as the automatic tooltip in bpython).

Upvotes: 1

Related Questions