0% found this document useful (0 votes)
48 views14 pages

Python File Handling: Types & Creation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views14 pages

Python File Handling: Types & Creation

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Files in python

In Python, a file is a named location in the non-volatile memory (like a hard disk) used to
permanently store related information or data. Python provides built-in functions, collectively
known as file handling, to interact with these files, enabling operations such as reading,
writing, and managing data.

Types of Files
In Python programming, files are primarily categorized into two main types based on how they
store and manage data: text files and binary files.
Additionally, Python utilizes specific file extensions to denote different kinds of Python-related
files for various purposes, such as source code, compiled bytecode, and type hinting.

Primary File Types in Python (by data handling)


When working with file handling functions in Python (like open()), files are treated as one of
two fundamental types:
• Text Files: These files store data as a sequence of human-readable characters
(alphabets, digits, and symbols). Each line in a text file is typically terminated by a
special End-of-Line (EOL) character, which is \n (newline) by default in Python.
o Examples: .txt, .py (Python source code files), .csv (Comma Separated
Values), .html, and .json files.
• Binary Files: These files store data in a non-human-readable binary format (0s and 1s)
that represents the actual content directly, rather than character encodings. Binary
files do not use EOL terminators and require specific software or programs to interpret
their contents correctly.
o Examples: Image files (.jpg, .png), audio files (.mp3, .wav), video files,
executable files, and compressed archives.
Python handles these two types differently during file operations. Text files are the default
mode ('t'), while binary files must be explicitly opened in binary mode using the 'b' character
(e.g., 'rb' for reading binary, 'wb' for writing binary).

Common Python-Specific File Extensions


Different file extensions indicate the file's purpose within the Python ecosystem:
• .py: Standard Python source code files. These are human-readable text files where you
write your programs.
• .pyc: Compiled Python bytecode files. When a .py file is run, the interpreter
automatically compiles it into bytecode and saves it as a .pyc file to speed up future
loading times of modules. These are binary files and not meant for human editing.
• .ipynb: Interactive Python Notebook files (Jupyter Notebook). These files combine live
code, output visualizations, and narrative text, commonly used in data science and
analysis.
• .pyi: Python interface (stub) files. These are used for adding type hints to existing code,
separating type annotations from the main implementation to keep the source code
clean or for backward compatibility with older code.
• .pyw: Windows GUI Python scripts. These are used to run Python programs that have
a graphical user interface (GUI) without opening the standard command prompt
console window.

Types of files
In Python, files are broadly categorized into two types: text files and binary files. The specific
file extensions a programmer interacts with (like .txt, .csv, .py, .png) fall under one of these
two fundamental types.
1. Text Files
Text files store data as human-readable characters, including alphabets, digits, and symbols.
Each line typically ends with an "End of Line" (EOL) character, which is \n (newline) by default
in Python.
Common examples of text files include:
• Plain text files (.txt): The simplest form of text storage.
o Example: Storing notes or simple configuration data.
• Source code files (.py): Files containing your Python code itself are text files.
o Example: A script named [Link] with print("Hello, world!").
• CSV files (.csv): Used to store tabular data where values are separated by commas.
o Example: A spreadsheet exported as a text file for data exchange.
• JSON files (.json): Used for storing structured data objects in a human-readable
format.
o Example: Storing settings for a program or API responses.
Example Code (Writing to a text file):
python
# Open a text file in write mode ('w')
with open('[Link]', 'w') as file:
[Link]('Hello, world!\n')
[Link]('This is a second line.')
The file is opened in text mode ('t'), which is the default, and the data is written as a standard
string.
2. Binary Files
Binary files store data in a machine-readable binary format (0s and 1s). Unlike text files, these
files do not have an EOL character and are not human-readable when opened with a standard
text editor. They require specific software to interpret their contents correctly. In Python, you
use the 'b' mode (e.g., 'rb', 'wb') to handle these files.
Common examples of binary files include:
• Image files (.png, .jpg, .gif): Store pixel data and other image information.
o Example: A photo or a program icon.
• Audio and Video files (.mp3, .mp4, .wav): Store compressed or raw media data.
o Example: A music track or movie clip.
• Compiled Python files (.pyc): Automatically generated by the Python interpreter to
speed up program loading by storing bytecode.
o Example: The interpreter creates these files in a __pycache__ directory.
• Executable files (.exe, .bin): Program files that the computer's operating system runs.
Example Code (Reading a binary file):
python
# Open an image file in binary read mode ('rb')
with open('[Link]', 'rb') as file:
binary_data = [Link]()
# The 'binary_data' variable now holds bytes, not human-readable text
# This data would be passed to an image processing library or similar tool

Python Create Text File


Using the open() function to create a new text file
To create a new text file, you use the open() function. The open() function has many
parameters. However, we’ll focus on the first two parameters:
f = open(path_to_file, mode)
In this syntax, the path_to_file parameter specifies the path to the text file that you want to
create.
For creating a new text file, you use one of the following modes:
• 'w' – open a file for writing. If the file doesn’t exist, the open() function creates a new
file. Otherwise, it’ll overwrite the contents of the existing file.
• 'x' – open a file for exclusive creation. If the file exists, the open() function raises an
error (FileExistsError). Otherwise, it’ll create the text file.
For example, the following creates a new file called [Link] and write some text into it:
with open('[Link]', 'w') as f:
[Link]('Create a new text file!')Code language: JavaScript (javascript)
This script creates a file with the name [Link] in the same directory where the script file
locates. If you want to create a file in a specified directory e.g., docs/[Link], you need
to ensure that the docs directory exists before creating the file. Otherwise, you’ll get
an exception. For example:
with open('docs/[Link]', 'w') as f:
[Link]('Create a new text file!')
Code language: Python (python)
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'docs/[Link]'Code language:
JavaScript (javascript)
In this example, Python raises an exception because the docs directory doesn’t exist.
Therefore, it could not create the [Link] file in that directory. To fix the issue, you need
to create the docs directory first and then create the [Link] file in that folder.
Also, you can handle the exception using the try-except statement as follows:
try:
with open('docs/[Link]', 'w') as f:
[Link]('Create a new text file!')
except FileNotFoundError:
print("The 'docs' directory does not exist")
Code language: Python (python)
Output:
The 'docs' directory does not existCode language: plaintext (plaintext)
If you don’t want to create a new text file in case it already exists, you can use the 'x' mode
when calling the open() function:
with open('[Link]', 'x') as f:
[Link]('Create a new text file!')Code language: Python (python)
Summary
• Use the open() function with the 'w' or 'x' mode to create a new text file.
Create a new file
In Python, you can create a new file using the built-in open() function with specific modes.
Using the with statement is the recommended practice because it ensures the file is
automatically closed, even if errors occur.
The primary modes for creating a file are 'w' (write) and 'x' (exclusive creation):
1. Using the 'w' mode (Write)
This is the most common method. It creates a new file if it does not exist. Caution: if a file
with the same name already exists, this mode will overwrite its entire content.
python
file_path = "[Link]"

# Open the file in write mode using a 'with' statement


with open(file_path, 'w') as file:
[Link]("Hello, world!\n")
[Link]("This text will be written to the file.")

print(f"File '{file_path}' created successfully.")


2. Using the 'x' mode (Exclusive Creation)
This mode is used for exclusive file creation. It ensures that a new file is created only if a file
with the same name does not already exist. If the file is found, Python will raise
a FileExistsError.
python
file_path = "unique_file.txt"

try:
# Open the file in exclusive creation mode
with open(file_path, 'x') as file:
[Link]("This file is created using the 'x' mode.")
print(f"File '{file_path}' created successfully.")

except FileExistsError:
print(f"Error: File '{file_path}' already exists.")
3. Using the 'a' mode (Append)
While primarily used for adding content to an existing file, the 'a' (append) mode will also
create a new file if the specified file does not exist. New data is always added to the end of
the file.
python
file_path = "append_mode_file.txt"

# Open the file in append mode


with open(file_path, 'a') as file:
[Link]("Initial line if file is newly created.\n")
[Link]("This line will be appended on subsequent runs.")

print(f"File '{file_path}' created or appended successfully.")


Key Practices
• Use with open(...): This statement automatically handles the closing of the file, which
is crucial for preventing file corruption and resource leaks.
• Specify a path: If you only provide a filename (e.g., "[Link]"), the file will be
created in the same directory as your Python script. To create it in a specific location,
use an absolute or relative path (e.g., "path/to/directory/[Link]").
• Handle directories: The open() function will raise a FileNotFoundError if you specify a
path where the intermediate directories do not exist. You can use the os module
(specifically [Link]()) to create necessary directories first.

How to create new binary file in python


To create a new binary file in Python, you open it using the built-in open() function with
the 'wb' mode (write binary) and write bytes objects or bytearray data to it.
Steps to Create a Binary File
1. Open the file in binary write mode ('wb'). Using a with statement is a best practice,
as it automatically handles file closure and resource management.
2. Prepare your data as bytes or a bytearray. All data written to a binary file must be in
byte format.
3. Write the data using the file object's write() method.
Example: Writing Raw Bytes
This example creates a file named [Link] and writes the ASCII values for "Hello" to it:
python
# Data must be a bytes object (prefixed with 'b') or bytearray
binary_data = b"Hello, Binary World!"
# Use the 'wb' mode to open the file for writing in binary format
with open("[Link]", "wb") as file:
[Link](binary_data)
print("Binary file '[Link]' created and data written successfully.")

Advanced: Writing Python Objects (Serialization)


For writing complex Python objects (like lists, dictionaries, or custom classes) directly to a
binary file, you can use the pickle module. This process is called serialization or "pickling".
python
import pickle

data_list = [10, 20, 30, 40, 50]


data_dict = {"name": "Alice", "age": 30}
combined_data = (data_list, data_dict)

# Open in 'wb' mode and use [Link]()


with open("data_objects.bin", "wb") as file:
[Link](combined_data, file)

print("Python objects pickled and written to 'data_objects.bin' successfully.")

You can read the data back using the 'rb' mode and [Link]():
python
import pickle

with open("data_objects.bin", "rb") as file:


loaded_data = [Link](file)

print(f"Loaded data: {loaded_data}")


Key Binary File Modes
When using the open() function, append the 'b' character to the mode string:
• 'wb': Write binary. Creates a new file or truncates (erases) the contents of an existing
file.
• 'ab': Append binary. Opens for writing; new data is added to the end of the file.
• 'rb': Read binary. Opens the file for reading only.
• 'wb+' or 'rb+': Opens for both reading and writing in binary format
File Handling in Python
File handling in Python involves interacting with files on your computer to read data from
them or write data to them. Python provides several built-in functions and methods for
creating, opening, reading, writing, and closing files.
Opening a File in Python
To perform any file operation, the first step is to open the file. Python's built-in open() function
is used to open files in various modes, such as reading, writing, and appending. The syntax for
opening a file in Python is −
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the file is
opened (e.g., 'r' for reading, 'w' for writing, 'a' for appending).
File Opening Modes
Following are the file opening modes −

[Link]. Modes & Description

R
1 Opens a file for reading only. The file pointer is placed at the beginning of the
file. This is the default mode.

Rb
2 Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.

W
5 Opens a file for writing only. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

B
6
Opens the file in binary mode

T
7
Opens the file in text mode (default)

+
8
open file for updating (reading and writing)

Wb
9 Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.

w+
10 Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

wb+

11 Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If the file does not exist, creates a new file for reading
and writing.

12 Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.
Ab

13 Opens a file for appending in binary format. The file pointer is at the end of the
file if the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.

a+

14 Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.

ab+

15 Opens a file for both appending and reading in binary format. The file pointer is
at the end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.

X
16
open for exclusive creation, failing if the file already exists

Once a file is opened and you have one file object, you can get various information related to
that file.
Example 1
In the following example, we are opening a file in different modes −
# Opening a file in read mode
file = open("[Link]", "r")

# Opening a file in write mode


file = open("[Link]", "w")

# Opening a file in append mode


file = open("[Link]", "a")

# Opening a file in binary read mode


file = open("[Link]", "rb")
Example 2
In here, we are opening a file named "[Link]" in binary write mode ("wb"), printing its name,
whether it's closed, and its opening mode, and then closing the file −
# Open a file
fo = open("[Link]", "wb")
print ("Name of the file: ", [Link])
print ("Closed or not: ", [Link])
print ("Opening mode: ", [Link])
[Link]()
It will produce the following output −
Name of the file: [Link]
Closed or not: False
Opening mode: wb

Reading a File in Python


Reading a file in Python involves opening the file in a mode that allows for reading, and then
using various methods to extract the data from the file. Python provides several methods to
read data from a file −
• read() − Reads the entire file.
• readline() − Reads one line at a time.
• readlines − Reads all lines into a list.
To read a file, you need to open it in read mode. The default mode for the open() function is
read mode ('r'), but it's good practice to specify it explicitly.
Example: Using read() method
In the following example, we are using the read() method to read the whole file into a single
string −
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Following is the output obtained −
Hello!!!
Welcome to TutorialsPoint!!!

Example: Using readline() method


In here, we are using the readline() method to read one line at a time, making it memory
efficient for reading large files line by line −
with open("[Link]", "r") as file:
line = [Link]()
while line:
print(line, end='')
line = [Link]()
Output of the above code is as shown below −
Hello!!!
Welcome to TutorialsPoint!!!
Example: Using readlines() method
Now, we are using the readlines() method to read the entire file and splits it into a list where
each element is a line −
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
print(line, end='')
We get the output as follows −
Hello!!!
Welcome to TutorialsPoint!!!

Writing to a File in Python


Writing to a file in Python involves opening the file in a mode that allows writing, and then
using various methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When opening a file in write
mode ('w'), the file's existing content is erased.
Example: Using the write() method
In this example, we are using the write() method to write the string passed to it to the file. If
the file is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a'
mode, it will append the string to the end of the file −
with open("[Link]", "w") as file:
[Link]("Hello, World!")
print ("Content added Successfully!!")
Output of the above code is as follows −
Content added Successfully!!
Example: Using the writelines() method
In here, we are using the writelines() method to take a list of strings and writes each string to
the file. It is useful for writing multiple lines at once −
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("[Link]", "w") as file:
[Link](lines)
print ("Content added Successfully!!")
The result obtained is as follows −
Content added Successfully!!

Closing a File in Python


We can close a file in Python using the close() method. Closing a file is an essential step in file
handling to ensure that all resources used by the file are properly released. It is important to
close files after operations are completed to prevent data loss and free up system resources.
Example
In this example, we open the file for writing, write data to the file, and then close the file using
the close() method −
file = open("[Link]", "w")
[Link]("This is an example.")
[Link]()
print ("File closed successfully!!")
The output produced is as shown below −
File closed successfully!!

Using "with" Statement for Automatic File Closing


The with statement is a best practice in Python for file operations because it ensures that the
file is automatically closed when the block of code is exited, even if an exception occurs.
Example
In this example, the file is automatically closed at the end of the with block, so there is no
need to call close() method explicitly −
with open("[Link]", "w") as file:
[Link]("This is an example using the with statement.")
print ("File closed successfully!!")
Following is the output of the above code −
File closed successfully!!
Handling Exceptions When Closing a File
When performing file operations, it is important to handle potential exceptions to ensure your
program can manage errors gracefully.
In Python, we use a try-finally block to handle exceptions when closing a file. The "finally"
block ensures that the file is closed regardless of whether an error occurs in the try block −
try:
file = open("[Link]", "w")
[Link]("This is an example with exception handling.")
finally:
[Link]()
print ("File closed successfully!!")
After executing the above code, we get the following output −
File closed successfully!!

You might also like