III Unit Files in Python
III Unit 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.
• 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.
• 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:
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.
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.
• Using readline()
• Using readlines()
Reading From a File Using read()
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.
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
L = ["Welcome To GFGC NAREGAL \n", "To Learn Python \n", "This is the best
programming language \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close() # to change file access modes
print()
print(file1.readline())
print()
file1.seek(0)
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(file1.readlines())
print()
file1.close()
OUTPUT:
The File myfile.txt contains
Hello
Welcome To GFGC NAREGAL
To Learn Python
This is the best programming language
Output of Readline function is
Hello
Hello
We
• 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
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:
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()
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt", "w") # write mode
file1.write("Tomorrow \n")
file1.close()
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']
['Tomorrow \n']
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:
• 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.
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:
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
Output
Welcome to TutorialsPoint:
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