Python Files Management - Reading File

Everything you’ve learned about raw_input and argv is so you can start reading files. You may have to play with this exercise the most to understand what’s going on, so do it carefully and remember your checks. Working with files is an easy way to erase your work if you are not careful.

In this exercise, we will read and write a file named 'pyfourm_file_exercise.txt". This file is a simple text file. with below text.

This tutorial is written on pyfourm.com
Autho is Akar Periwal

What we want to do is “open” that file in our script and print it out. However, we do not want to just “hard code” the name into our script. “Hard coding” means putting some bit of information that should come from the user as a string right in our program. That’s bad because we want it to load other files later. The solution is to use argv and input to ask the user what file the user wants instead of “hard coding” the file’s name.

If you don't remember about argv then read chapter 7

If you don't remember about input function then read chapter 6.

Exercise 1:

In line 4 & 10, we opened the file and assigned it to a parameter 'txt' & 'txt_again'.

Output:

Pyfourm.com

We can read a file using for loop also, this is useful when you want to take some action on data you get from the file. e.g

This time our file is pyfourm_file_exercise_02.txt and contain:

Akar Periwal, Author
James Bond, User
Spiderman, User

Exercise 2:

Line 5, When you use for loop to open a file, parameter 'i' will contain each line in the file. e.g 
First time 'i' will be: Akar Periwal, Author.   This doesn't contain 'User' Keyword so it will give false at line 6.
Second time 'i' will be: James Bond, User.   This line contains the 'User' keyword so it will give True at line 6.

Line 7: we split 'i' with ',' keyword. This will return 2 values which will be saved in name and role.

Output

 

Exercise:

Try opening multiple files and apply some conditions to print.

 

About the author

akarperiwal

0 Comments

Please login to comment