Python

 

 

 

 

Python - File Operation/Management

 

File operations and management are essential when you need to work with external files for reading, writing, or processing data. Python provides built-in functions and libraries that make it easy to open, read, write, and close files, as well as manage file paths and directories.

 

Here is an overview of the key concepts and functions related to file operations and management in Python:

  • Opening files: To work with a file, you first need to open it using the built-in open() function. This function takes two main arguments: the file path and the mode in which the file should be opened. The mode can be 'r' for reading, 'w' for writing, 'a' for appending, and 'x' for exclusive creation. Additionally, you can specify if the file should be opened in binary ('b') or text ('t') mode. By default, the mode is 'rt', which means the file is opened for reading in text mode.
  • Closing files: After you are done working with a file, it's important to close it using the close() method of the file object. This releases the resources associated with the file and ensures that any changes made to the file are saved. To automatically close a file after use, you can use the with statement, which creates a context manager that takes care of closing the file when the block of code inside the with statement is done.
  • Reading files: To read the contents of a file, you can use methods like read(), readline(), and readlines(). The read() method reads the entire file into a single string, while readline() reads a single line at a time, and readlines() reads all lines into a list. You can also loop through the file object itself to read the file line by line.
  • Writing files: To write data to a file, you can use the write() and writelines() methods of the file object. The write() method writes a single string to the file, while writelines() writes a list of strings to the file. Note that when opening a file in 'w' mode, the file's existing content will be overwritten.
  • File management: The os and shutil libraries provide various functions for file management, such as creating directories, renaming or deleting files, and working with file paths. Some key functions from these libraries include os.mkdir(), os.rename(), os.remove(), os.path.join(), os.path.exists(), os.path.isfile(), os.path.isdir(), and shutil.copy().

 

 

 

Examples

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Read the whole text file with single read() - Example 1
  • Read the file line by line with for loop - Example 2
  • Read the file line by line with while loop - Example 3
  • Write text into a file - Example 4

 

 

< Syntax >

  • file fHandle = open(file_name [, access_mode][, buffering])
  • fHandle.read()
  • fHandle.read(count)
  • fHandle.readline()
  • fHandle.write(string)
  • fHandle.write(integer)
  • fHandle.write(ListOfInteger)
  • fHandle.close()

 

Mode

Description

r

Read only.

rb

Read only in binary format

r+

Read and Write

rb+

Read and Write in binary format

w

Write only

wb

Write only in binary format

w+

Write and Read

wb+

Write and Read in binary format

a

Append

ab

Append in binary format

a+

Append and Read

ab+

Append and Read in binary format

 

 

< Examples >

 

Data File used in this example : Following is the contents in data file (in text format) that is used in following examples.

Since I would not specify path of the file, this file should be in the same folder as the example script file

 

< data.txt >

Line 1 : Data 1

Line 2 : Data 2

Line 3 : Data 3

Line 4 : Data 4

Line 5 : Data 5

 

 

< Example 1 >

 

fHandle = open("data.txt","r")

 

readStr = fHandle.read()

print(readStr)

 

fHandle.close()

 

Result :--------------------------------

 

Line 1 : Data 1

Line 2 : Data 2

Line 3 : Data 3

Line 4 : Data 4

Line 5 : Data 5

 

 

< Example 2 >

 

fHandle = open("data.txt","r")

 

for readStr in fHandle :

    print(readStr)

 

fHandle.close()

 

Result :--------------------------------

Line 1 : Data 1

 

Line 2 : Data 2

 

Line 3 : Data 3

 

Line 4 : Data 4

 

Line 5 : Data 5

 

 

< Example 3 >

 

fHandle = open("data.txt","r")

 

while 1:

    readStr = fHandle.readline()

    if not readStr:

        break

    print(readStr)

 

fHandle.close()

 

Result :--------------------------------

Line 1 : Data 1

 

Line 2 : Data 2

 

Line 3 : Data 3

 

Line 4 : Data 4

 

Line 5 : Data 5

 

 

< Example 4 >

 

fHandle = open("output.txt","w")

 

for i in range(1,5) :

   fHandle.write("Line "+str(i)+"\n")

 

fHandle.close()

 

Result :--------------------------------

You should see output.txt file is created with following contents

Line 1

Line 2

Line 3

Line 4