Python Functions and Files

In previous chapter I explained how you can use functions and use it. In this chapter we will see some exercise to manage file with python functions. I will show you some more functions for managing files.

Exercise

from sys import argv
script, input_file = argv
def print_all(f):
print (f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print (line_count, f.readline())
current_file = open(input_file)
print ("First let's print the whole file:\n")
print_all(current_file)
print ("Now let's rewind, kind of like a tape.")
rewind(current_file)
print ("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)

 

To run this code we will need a file. I am using a file with below text.

Hello This is my file
I am Akar Periwal
and my website is https://pythoninhindi.shiksha
you can check my other websites also on https://aakarperiwal.com
or for network you can check https://solvethenetwork.com

Run the code

Try running this code

Files with Python Functions

Understand this code

  • We are passing filename as argument to script.
  • We can define function any time in script even after starting your main script
  • readline function (its predefine function in python, which is used with files).┬áInside readline() is code that scans each byte of the file until it finds a \n character(\n represent new line), then stops reading the file to return what it found so far. The file f is responsible for maintaining the current position in the file after each readline() call, so that it will keep reading each line

If you still have doubt you can ask me on comment.. Remember clear doubt now so that you can move to next chapter ease..

Exercise of the day

Just try these function and read file with readline.

 

 

no comments

Leave me comment