Presentation is loading. Please wait.

Presentation is loading. Please wait.

IIITD File Input / Output In Python. File and operations  File is a named location on disk to store related information  When we want to read from or.

Similar presentations


Presentation on theme: "IIITD File Input / Output In Python. File and operations  File is a named location on disk to store related information  When we want to read from or."— Presentation transcript:

1 IIITD File Input / Output In Python

2 File and operations  File is a named location on disk to store related information  When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.  Hence, in Python, a file operation takes place in the following order.  Open a File  Read or Write(operation)  Close the file

3 Opening a file with file modes  Python has a built-in function open() to open a file.  f = open("test.txt")  f = open("C:/Python33/README.txt")  Modes of opening a file  ‘r’-Reading(default)  ‘w’-Opening for writing  f = open("test.txt",'w')  ‘a’-Open for appending at the end of file

4 Writing to a file  In order to write into a file we need to open it in write 'w‘ or append 'a‘ mode  f.write("my first file\n")  f.write("This file\n\n")  f.write("contains three lines\n")  This method does not return anything

5 Reading from a File  f.read(4) # read the first 4 data  f.read() # read in the rest till end of file  f.tell() # get the current file position  f.seek(0) # bring file cursor to initial position

6 Contd..  print(f.read())  for line in f:... print(line, end = '')  The lines in file itself has a newline character '\n'. Moreover,the print() function also appends a newline by default. Hence, we specify the end parameter to avoid two newlines when printing.

7 Contd..  Alternately, we can use readline() method to read individual lines of a file  f.readline()-to read individual lines of a file. This method reads a file till the newline, including the newline character.  f.readlines()-method returns a list of remaining lines of the entire file.

8 The OS module  Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files  os.rename(current_file_name, new_file_name)  os.remove(file_name)

9 Take away  Count number of words in a file  Count most frequent word in a file.


Download ppt "IIITD File Input / Output In Python. File and operations  File is a named location on disk to store related information  When we want to read from or."

Similar presentations


Ads by Google