About Python File Handling

tags: #python/documentation/file_handling

What is Python File Handling?

File handling in Python allows you to interact with files on your computer. It includes operations like:

Python provides built-in functions and methods for file handling.


Opening a File

To open a file, you use the open() function. It returns a file object that you can use to perform various file operations.

file = open('filename.txt, 'mode')

# file name extention depends on the type of file being read (e.g., csv or txt)
Assumptions

  1. The requested file exists.
  2. The requested file is in the same directory as the Python program (otherwise, pass the file path).
  3. You have proper permission to read the file.

Prompting a User for a File Name

fname = input('Enter file name: ')
file = open(fname) # open file

Reading a File

There are three ways in which you can read the file object:

1. Reading the Entire File Using read()

Description

This is to read all text from a file into a single string. This method is useful if you have a small file and you want to manipulate the whole text of that file.

file.read()

# to store the string in a var
content = file.read()

2. Reading the Line-by-Line Using readline()

Description

To read the text file line by line and return all the lines as strings.

# Store lines in list
lines = list()

for line in file.readline():
	lines.append(line)


# Printing line
for line in file.readlines():
	print(line)

3. Returning a List of Lines as Str Using readlines()

Description

Read all the lines of the text file and return a list of lines in the file as strings. This is the most popular approach.

file.readlines()

# to print each line in the list
for line in file.readlines():
	print(line)
What is a Newline Character?

To break the file into lines, we can use a special character called the newline (\n) to indicate when a line ends and the beginning of another line of text. We do not see these characters are they are considered 'whitespaces'.

When using readlines(), each line in the list includes the newline character ('\n') at the end. To remove the newline character, use the str.strip() method on each line.

Removing the Newline Character
lines = file.readlines()

# modify list directly
for i in range(len(lines)):
	lines[i] = line[i].strip()


# alternative method
lines = [line.strip() for line in file.readlines()]
Powered by Forestry.md