Categories
Uncategorized

Reading Files – Python

Just a quickie on files and how to read them.

To read a file you can use with open(), adding then the path to the file and giving it a name.

with open('path/toMy/file.txt') as file_my_file:

Then you can read the file using either read() or readlines().

Read()

Using read() will mean that the entire file will be read and stored as a string.

>>> with open('path/toMy/file.txt') as file_my_file:
...    str_file_contents=file_my_file.read()

# so if we check what type of data it is..
>>> type(str_file_contents)
<type ' str'>
# there we go...a string.

So if you have a file like this

This is line 1.
This is line 2.
This is line 3.

if you use read() you will end up with something like this

'This is line 1.\nThis is line 2.\nThis is line 3.'

Readlines()

On the other hand, using readlines() will give you a list, where each file line is an item, like this.

>>> with open('path/toMy/file.txt') as file_my_file:
...    str_file_contents=file_my_file.readlines()

# so if we check what type of data it is..
>>> type(list_file_contents)
<type ' list'>
# there we go...a list.

So now, it looks more like this

['This is line 1.\n','This is line 2.\n','This is line 3.']

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s