1.what is the difference between read() ,readline() and readlines() ?
Ans.read()
Feature | Description |
Purpose | Reads the entire file as a single string. |
Returns | A single string (str) |
Usage | file.read() or file.read(n) to read n characters |
Note | Not memory-efficient for large files |
Example:
f = open(“data.txt”, “r”)
text = f.read()
print(text)
f.close()
—————-
What happens if we pass a value in read(5) in Python?
When you pass a number to read(n), it tells Python to read exactly n characters (or bytes in binary mode) from the file, starting from the current position of the file pointer.
2. Print all characters from a file by using a loop 👍
3. Count the total no of characters:
4.Use of sleep() Function in Python
The sleep() function is used to pause the execution of a program for a specified amount of time (in seconds).
What is the difference between text file and binary file?
Feature | Text File | Binary File |
Representation | Contains human-readable text. | Contains non-human-readable binary data. |
Encoding | Typically encoded using ASCII or Unicode. | No specific encoding; stores raw bytes. |
Readability | Readable by humans. | Not readable by humans. |
Size | Text files tend to be larger due to character encoding overhead. | Binary files may be smaller due to lack of character encoding. |
Editing | Easily edited with a text editor. | Not easily edited directly; usually requires specialized software. |
Portability | Generally more portable across different platforms and systems. | May have issues with portability due to differences in binary representations. |
Usage | Commonly used for storing textual data such as configuration files, logs, and documents. | Used for storing non-textual data like images, audio, video, and executable programs. |
Types of text file:
What is regular text file?
A regular text file, often simply referred to as a “text file,” is a type of file that contains human-readable text encoded in a specific character encoding scheme, such as ASCII or Unicode. It typically consists of lines of text, with each line terminated by a newline character. Text files are commonly used for storing plain text data, such as program source code, configuration files, documentation, and more. They can be created and edited using any text editor.
What is a Delimited text file?
A delimited text file is a type of text file where the data is organized into rows and columns, with each column separated or delimited by a specific character or sequence of characters, such as commas, tabs, semicolons, or pipes. This delimiter serves to distinguish between individual fields or values within each row of the file. Delimited text files are commonly used for storing structured data, such as spreadsheets or database exports, and are easily readable and parseable by various software applications. Common examples include CSV (Comma-Separated Values) files and TSV (Tab-Separated Values) files.
What is a binary file?
A binary file is a type of file that stores data in a format that is not directly human-readable. Instead of storing text or characters, binary files store data in the form of binary digits (bits), typically representing numbers, images, audio, video, executable code, or other non-textual information. Binary files are composed of sequences of bytes, where each byte represents a group of eight bits. Unlike text files, which can be opened and edited with a text editor, binary files require specialized software or tools to interpret and manipulate their contents. Examples of binary files include image files (e.g., JPEG, PNG), audio files (e.g., MP3, WAV), video files (e.g., MP4, AVI), and executable files (e.g., EXE, DLL).
What is raw string in python?
Python raw string treats the backslash character (\) as a literal character. Raw string is useful when a string needs to contain a backslash, such as for a regular expression or Windows directory path, and you don’t want it to be treated as an escape character.
print(r”how are you\nwe are indian”)
How to append write in a file?
How to write multiple data in list format in a file?
#wap to count the number of vowels and consonants in file
f=open(“myfile.txt”,”r”)
x=f.read()
c=0
v=0
for ch in x:
if ch==’a’ or ch==’A’or ch==’e’or ch==’E’or ch==’i’or ch==’I’or ch==’o’or ch==’O’or ch==’u’or ch==’U’:
v=v+1
else:
c=c+1
print(“number of vowels in file”,v)
print(“number of consonents in file”,c)
#wap to count the number of words in a file
def count_words_in_file(file_name):
with open(file_name, ‘r’) as file:
text = file.read()
words = text.split() # Split the text into words using whitespace as delimiter
return len(words)
file_name = ‘myfile.txt’ # Change this to your file’s name
word_count = count_words_in_file(file_name)
print(“Number of words in the file:”, word_count)
What is flush()?
In Python, flush refers to the action of forcibly writing any buffered data to a file or an output stream, ensuring that it’s immediately available for consumption or processing.
When you write to a file or an output stream (like standard output), the data you write might not be immediately written to the underlying file or device. Instead, it may be held in a buffer temporarily for efficiency reasons. This buffered data will eventually be written to the file or device, but the timing can depend on various factors such as the size of the buffer, the operating system’s behavior, or the stream’s settings.
The flush method allows you to manually trigger the writing of buffered data. When you call flush on a file object or an output stream, it ensures that any buffered data associated with that file or stream is immediately written out.
p=open(“‘myfile.txt”,”w+”)
name=input(“enter a name”)
p.write(name)
p.seek(0)
x=p.read()
print(x)
p.flush()
p.close()
What is the use of seek()?
In Python, seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file. from_what: It defines point of reference. Returns: Return the new absolute position.
f = open(“demofile.txt”, “r”)
f.seek(4)
print(f.readline())
——————————————————————————————–
In Python, double backslash (\\) is used in file paths because the single backslash (\) is an escape character in strings.
Why is \ an escape character?
In Python strings, \ is used to introduce special characters, such as:
\n → new line
\t → tab
\” → double quote
\\ → a literal backslash
So if you write:
path = “C:\newfolder\test.txt”
Python will interpret \n as a newline and \t as a tab, resulting in unexpected behavior.
Correct way: Use \\ to escape the backslash
To represent a literal backslash, use \\:
path = “C:\\newfolder\\test.txt”
This tells Python to treat each \\ as a single \ in the actual path.
Alternative (better) ways:
1. Raw String (recommended for Windows paths):
path = r”C:\newfolder\test.txt”
The r before the string tells Python: “treat backslashes as literal characters”, so \n won’t become a newline.
2. Use forward slashes /, even on Windows:
Python accepts:
path = “C:/newfolder/test.txt”
This is often the easiest and cleanest way.
Format | Works? | Explanation |
“C:\newfolder\test” | NO | \n and \t are escape characters |
“C:\\newfolder\\test” | YES | Escapes backslashes |
r”C:\newfolder\test” | YES | Raw string (no escape processing) |
“C:/newfolder/test” | YES | Forward slashes (cross-platform) |
Write in a file:
p=open(“abc.txt”,”a”)
s=input(“enter a line”)
p.write(s)
p.close()
How to write multiple lines in a file. Use of writelines() function:
p=open(“abc.txt”,”w”)
l1=[]
for i in range(5):
s=input(“enter a name”)
l1.append(s+”\n”)
p.writelines(l1)
p.close()
Functions of readline()
Observe the above image carefully:
Code Explanation
p = open(“abc.txt”, “r”) # Open file abc.txt in read mode
x = p.readline(10) # Read up to 10 characters from the first line
print(x)
x = p.readline(5) # Read up to 5 characters from the remaining part of the same line
print(x)
x = p.readline(12) # Read up to 12 characters from the same or next line
print(x)
The argument inside readline(n) means:
- Read up to n characters, stopping early if a newline (\n) is encountered.
Step-by-step Output and Reason:
- p.readline(10)
Reads first 10 characters from line 1:
Write a pr
- ✅ Output: ‘Write a pr’
- p.readline(5)
Continue reading next 5 characters from the same line:
ogram
So, next 5 characters: “ogra” (m not included yet)
✅ Output: ‘ogra’
- p.readline(12)
Continues reading from current position on the same line.
Remaining part of first line is:
m that generates the Lucas series up to N terms.
Next 12 characters: “m that genera”
Output: ‘m that genera’
✅ Final Output on Screen:
Write a pr
ogra
m that genera
Function Call | What It Does |
readline(n) | Reads up to n characters or until a newline (\n) |
File reading | Continues from where the last read stopped |
Partial line reads | Do not reset line; reads from current position |
Count the number of lines in a file: