Python File Handling

Python File Handling:

File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.

1. open( ) function in file handling:-

The key function for working with files in Python is the open() function.
The open() function takes two parameters: (filename) and (mode).

There are four different methods (modes) for opening a file:

1"r" - Read - Default value. Opens a file for reading, error if the file does not exist.

2. "a" - Append - Opens a file for appending, creates the file if it does not exist.

3. "w" - Write - Opens a file for writing, creates the file if it does not exist.

4. "x" - Create - Creates the specified file, returns an error if the file exists.


In python you can specify if the file should be handled as binary or text mode.

1."t" - Text - Default value. Text mode.

2."b" - Binary - Binary mode (e.g. images)


Opening a file:

To open a file for reading it is enough to specify the name of the file:

Example:

f = open("pythonfile.txt")

We can write above code in a other way also, given below:

Example:

f = open("pythonfile.txt""rt")

Note: "r" for read, and "t" for text are the default values, we do not need to specify them.


Assume that we have save the below content in pythonfile.txt:-

Hello,Python 
Welcome pythonist


Reading a file:

read() method is used for reading the content of the file.

Example:

f = open("pythonfile.txt""r")
print(f.read())

Output:
Hello,Python
Welcome pythonist


read() method returns the whole text, but you can also specify how many characters you want to return.

Example:

f = open("pythonfile.txt""r")
print(f.read(6))

Output:
Hello,


Read Lines method( ):

We can return one line by using the readline() method.

Example:

f = open("pythonfile.txt""r")
print(f.readline())

Output:
Hello,Python

Another method is readlines() method returns a list containing each line in the file as a list item.

Example:

f = open("pythonfile.txt""r")
print(f.readlines())

Output:
['Hello,Python\n', 'Welcome pythonist']

By calling readline() two times, you can read the two first lines.

Example:

f = open("pythonfile.txt""r")
print(f.readline())
print(f.readline())

Output:
Hello,Python
Welcome pythonist

By looping through the lines of the file, you can read the whole file, line by line.

Example:

f = open("pythonfile.txt""r")
for x in f:
  print(x)


Output:
Hello,Python
Welcome pythonist


Writing a file:

To write to an existing file, you must add a parameter to the open() function.

"a" - Append,this will append to the end of the file.

"w" - Write,this will overwrite any existing content.

Example:

f = open("pythonfile.txt""a")
f.write("New Content!")
f.close()

#open and read the file after the appending:f = open("pythonfile.txt""r")
print(f.read())

Output:
Hello,Python
Welcome pythonist New Content!

To overwrite the content of file we "w".

Example:

f = open("pythonfile3.txt""w")
f.write("Content overwrited!")
f.close()

#open and read the file after the appending:
f = open("pythonfile3.txt""r")
print(f.read())

Output:
Content overwrited!


Creating a file:

To create a new file, use the open() method, with one of the following parameters.

Example:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example:

f = open("myfile.txt""x")

Output: A new file is created.

Example:

f = open("myfile.txt""w")

Output: create a new file if file does not exist.


Closing a file:

Example:

f = open("pythonfile.txt""r")
print(f.readline())
f.close()

# This will close the file.


Deleting a file and folder:

To delete a file, import the OS module, and run its os.remove() function.

Example 1:

import os
os.remove("pythonfile.txt")

To delete an entire folder, use the os.rmdir() method.

Example 2:

import os
os.rmdir("myfolder")

Note: You can remove only empty folder.


File methods:

1. fileno() method returns the file descriptor of the stream, as a number.

Example:

f = open("pythonfile.txt""r")
print(f.fileno())

Output:
4


2.flush() method cleans out the internal buffer.

Example:

f = open("pythonfile.txt""a")
f.write("Now the file has one more line!")
f.flush()
f.write("...and another one!")

#Now we will read the file the output will be:
...and another one!


3. isatty() method returns True if the file stream is interactive, example: connected to a terminal.

Example:

f = open("demofile.txt""r")
print(f.isatty())

Output:
False


4. readable() method returns True if the file is readable, False if not.

Example:

f = open("demofile.txt""r")
print(f.readable())

Output:
True


5. writable() method returns True if the file is writable, False if not.

Example:

f = open("pythonfile.txt""a")
print(f.writable())

Output:
True


6. seek() method sets the current file position in a file stream and return new position.

Example:

f = open("pythonfile.txt""r")
f.seek(4)
print(f.readline())

Output:
ome pythonist


7. seekable() method returns True if the file is seekable, False if not.

Example:

f = open("pythonfile.txt""r")
print(f.seekable())

Output:
True


8. tell() method returns the current file position in a file stream.

Example:

f = open("pythonfile.txt""r")
print(f.tell())

Output:
0


9. truncate() method resizes the file to the given number of bytes.If the size is not specified, the current position will be used.

Example:

f = open("pythonfile.txt""a")
f.truncate(5)
f.close()

#open and read the file after the truncate:f = open("pythonfile.txt""r")
print(f.read())

Output:
Hello


10. writelines() method writes the items of a list to the file.

Example:

f = open("pythonfile.txt""a")
f.writelines(["End"])
f.close()

#open and read the file after the appending:f = open("pythonfile.txt""r")
print(f.read())

Output:
Hello,Python
Welcome pythonist End

Post a Comment

0 Comments