0% found this document useful (0 votes)
3 views

III Unit Files in Python

The document provides an overview of file handling in Python, detailing the types of files (text and binary) and their characteristics. It explains how to open, read, write, and append to text files using built-in functions like open(), read(), write(), and writelines(). Additionally, it discusses algorithms that utilize file-reading techniques and methods for transferring files over the internet.

Uploaded by

MyDream 4U
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)
3 views

III Unit Files in Python

The document provides an overview of file handling in Python, detailing the types of files (text and binary) and their characteristics. It explains how to open, read, write, and append to text files using built-in functions like open(), read(), write(), and writelines(). Additionally, it discusses algorithms that utilize file-reading techniques and methods for transferring files over the internet.

Uploaded by

MyDream 4U
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
You are on page 1/ 16

READING AND WRITING FILES IN PYTHON

Python provides built-in functions for creating, writing, and reading files. Two types
of files can be handled in Python: normal text files and binary files (written in binary
language, 0s, and 1s).

• Text files: In this type of file, each line of text is terminated with a special
character called EOL (End of Line), which is the new line character ('\n') in
Python by default.

• Binary files: In this type of file, there is no terminator for a line, and the data is
stored after converting it into machine-understandable binary language.

KINDS OF FILES IN PYTHON


Python interacts with various file types, categorized primarily as text files and binary
files.

• Text Files:

These files store data as human-readable characters. Each line typically ends with a
special character denoting the end-of-line (EOL), which defaults to a newline
character ("\n") in Python. Common text file types include:
o .txt: Plain text files for general text storage.

o .csv: Comma-separated values files for tabular data.


o .log: Log files for recording events.

o .ini: Configuration files storing settings in key-value pairs.


o .py: Python source code files.

o .json: JavaScript Object Notation files for data interchange.

o .yaml: Human-readable data serialization format.

o .html: Hypertext Markup Language for web pages.

• Binary Files:
These files store data in binary format (0s and 1s), not directly human-readable. They
require specific programs or software to interpret their content. Examples include:

o Images (.jpg, .png, .gif, etc.)

o Audio files (.mp3, .wav, etc.)

o Video files (.mp4, .avi, etc.)


o Executable files (.exe, etc.)
o .pdf: Portable Document Format.

o .zip: Compressed archives.

o Pickle files: Serialized Python objects.

Python provides built-in functions to handle these file types, allowing for
operations such as creating, reading, writing, and modifying files. The open()
function is central to file handling, accepting a file path and mode (e.g., read "r",
write "w", append "a", binary "b") as arguments.

Opening a Text File in Python

It is done using the open() function. No module is required to be imported for this
function.

Example: Here, file1 is created as an object for MyFile1 and file2 is created as an
object for MyFile2.

Python Read Text File

There are three ways to read a text file in Python:


• Using read()

• Using readline()
• Using readlines()
Reading From a File Using read()

• read(): Returns the read bytes in form of a string. Reads n bytes, if no n


specified, reads the entire file.

Reading a Text File Using readline()

readline(): Reads a line of the file and returns in form of a string.For specified n,
reads at most n bytes. However, does not reads more than one line, even if n
exceeds the length of the line.

Reading a File Using readlines()

readlines(): Reads all the lines and return them as each line a string element in a list.

Example: In this example, a file named "myfile.txt" is created and opened in write
mode ( "w" ). Data is written to the file using write and writelines methods. The file is
then reopened in read and append mode ( "r+" ). Various read operations, including
read , readline , readlines , and the use of seek , demonstrate different ways to
retrieve data from the file. Finally, the file is closed

file1 = open("myfile.txt", "w")

L = ["Welcome To GFGC NAREGAL \n", "To Learn Python \n", "This is the best
programming language \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)
file1.close() # to change file access modes

file1 = open("myfile.txt", "r+")


print("Output of Read function is ")
print(file1.read())

print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print("Output of Readline function is ")

print(file1.readline())

print()
file1.seek(0)

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()

file1.seek(0)
print("Output of Readline(9) function is ")

print(file1.readline(9))

file1.seek(0)
# readlines function

print("Output of Readlines function is ")

print(file1.readlines())
print()

file1.close()
OUTPUT:
The File myfile.txt contains

Program OUTPUT is:


Output of Read function is

Hello
Welcome To GFGC NAREGAL

To Learn Python
This is the best programming language
Output of Readline function is

Hello

Output of Read(9) function is

Hello
We

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'Welcome To GFGC NAREGAL \n', 'To Learn Python \n', 'This is the best
programming language \n']

Write to Text File in Python

There are two ways to write in a file:


• Using write()

• Using writelines()
Writing to a Python Text File Using write()

• write(): Inserts the string str1 in a single line in the text file.

Output:
Enter the name of the employee: ram

Enter the name of the employee: kiran

Enter the name of the employee: arun

Data is written into the file.


Writing to a Text File Using writelines()

writelines(): For a list of string elements, each string is inserted in the text file.Used
to insert multiple strings at a single time.

Output:

Enter the name of the employee: ram


Enter the name of the employee: kiran

Enter the name of the employee: arun


Data is written into the file.
Appending to a File in Python
In this example, a file named "myfile.txt" is initially opened in write mode ( "w" ) to
write lines of text. The file is then reopened in append mode ( "a" ), and "Today" is
added to the existing content. The output after appending is displayed using
readlines . Subsequently, the file is reopened in write mode, overwriting the content
with "Tomorrow". The final output after writing is displayed using readlines.

file1 = open("myfile.txt", "w")

L = ["Welcome to GFGC NAREGAL \n", "To Study BCA \n", "This is Best College\n"]
file1.writelines(L)

file1.close()
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode

file1.write("Today \n")

file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after appending")

print(file1.readlines())
print()

file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt", "r")


print("Output of Readlines after writing")

print(file1.readlines())

print()

file1.close()
Output:
Output of Readlines after appending

['Welcome to GFGC NAREGAL \n', 'To Study BCA \n', 'This is Best College\n', 'Today
\n']

Output of Readlines after writing

['Tomorrow \n']

Closing a Text File in Python

Python close() function closes the file and frees the memory space acquired by that
file. It is used at the time when the file is no longer needed or if it is to be opened in
a different file mode.

File_object.close()
ALGORITHMS THAT USE THE FILE-READING TECHNIQUES IN PYTHON
Several algorithms utilize file-reading techniques in Python, often depending on the
specific task and data structure. Some common examples include:

• Data analysis and processing:


Algorithms designed for data analysis frequently read data from files. For example, a
program analyzing customer purchase history might read data from a CSV file,
process it, and then output insights. Libraries like Pandas are often used for this
purpose, providing efficient ways to read and manipulate data from various file
formats.

• Search algorithms:
Algorithms that search for specific patterns or information within a file, such as
finding a particular word or phrase in a text file, rely on file reading. These
algorithms may read the entire file into memory or process it line by line, depending
on the size and structure of the file.

• Sorting algorithms:

When dealing with large datasets that cannot fit into memory, sorting algorithms
may read data from a file in chunks, sort each chunk, and then merge the sorted
chunks to produce a fully sorted output. This approach is known as external sorting.

• Text processing algorithms:


Algorithms that perform text analysis, such as natural language processing tasks,
often read text from files. These algorithms may involve tokenizing the text, counting
word frequencies, or identifying specific grammatical structures.
• Configuration file parsing:

Many applications use configuration files to store settings and parameters.


Algorithms that parse these files read the data and use it to configure the
application's behaviour. Common file formats for configuration files include JSON,
YAML, and INI.

• Data validation and cleaning:

Algorithms designed to validate and clean data often read data from files, check for
errors or inconsistencies, and then output a corrected version of the data. This
process may involve checking data types, removing duplicates, or handling missing
values.
FILES OVER THE INTERNET IN PYTHON
Transferring files over the internet in Python can be achieved through several
methods, each suitable for different scenarios:

1. Using the requests library (HTTP)


The requests library is a versatile tool for making HTTP requests, including
downloading and uploading files.

2. Using urllib.request

The urllib.request module provides functions for fetching data across the web.
3. Using FTP (ftplib)
For interacting with FTP servers, Python's ftplib module can be utilized.

4. Socket programming

For more control over the transfer process, you can use sockets to establish a
connection and send/receive data.
Handling large files

For large files, reading and sending data in chunks can be more efficient.
MULTILINE RECORDS IN PYTHON
1) Using writelines() Function

This function writes several string lines to a text file simultaneously. An iterable
object, such as a list, set, tuple, etc., can be sent to the writelines() method.
Syntax

Example - 1

Output

Example - 2

Output

Welcome to TutorialsPoint

Write multiple lines


Done successfully
3) Using while loop
Example - 3:

Output
Welcome to TutorialsPoint:

The next line is printed successfully:

4) Using the writelines() Function

If you want to add more lines to an existing text file, you must first open it in append
mode and then use the writelines() function, as seen below.
Example-4

Output

Welcome to TutorialsPoint
Write multiple lines
Done successfully
Adding lines
writing into it
written successfully

You might also like