Search This Blog

Thursday, March 21, 2019

File operations in Python


The different file operation in Python are
  • Open a file
  • Read or write
  • Close the file

Open()

Python has a built-in function open() to open a file. The open() function is used to open files in our system, the filename is the name of the file to be opened.

f = open("<Filename>")

We can specify the mode while opening a file. In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the file.

The default is reading in text mode. In this mode, we get strings when reading from the file.

Example

filename = "hello.txt"
file = open(filename, "r")
for line in file:
   print line,

Read ()

The read functions contains following methods
  • read()           #return one big string
  • readline        #return one line at a time
  • readlines       #returns a list of lines

Write ()

This method writes a sequence of strings to the file.
  • write ()          #Used to write a fixed sequence of characters to a file
  • writelines()    #writelines can write a list of strings.

Append ()

The append function is used to append to the file instead of overwriting it.
To append to an existing file, simply open the file in append mode ("a")

Close()

When you’re done with a file, use close() to close it and free up any system
resources taken up by the open file

File Handling Examples

To open a text file, use:
f = open("hello.txt", "r")


To read a text file, use:
f = open("hello.txt","r")
print(f.read())


To read one line at a time, use:
f = open("hello".txt", "r")
print(f.readline())


To read a list of lines use:
f = open("hello.txt.", "r")
print(f.readlines())


To write to a file, use:
f = open("hello.txt","w")
write("Hello World")
f.close()


To write to a file, use:
f = open("hello.txt", "w")
text_lines = ["text line 1", "text line 2", "text line 3"]
f.writelines(text_lines)
f.close()


To append to file, use:
f = open("hello.txt", "a")
write("Hello World again")
f.close()


To close a file, use
f = open("hello.txt", "r")
print(f.read())
f.close()

No comments:

Post a Comment