FileHandling2023 Text File-1
FileHandling2023 Text File-1
TEXT FILE
BINARY FILE
CSV FILE
TEXT FILES
Stores information in ASCII or Unicode characters
Each line of text is terminated with a special
character known as EOL – End Of Line character
(‘\n’, ‘\r \n’)
Internal translations take place when EOL is read
or written
Extension for text files is .txt
Default mode of file
TEXT FILE
No translations required
More secure
CSV FILES
Update Search
<file_objectname> = open(<filename>)
OR
<file_objectname> = open(<filename>, <mode>)
F = open(r“d:\mydata\poem.txt”,”r”)
• Another solution of double backslash is using “r” before the
path making the string as raw string
i.e. no special meaning attached to any character
OPENING FILES
• The default file-open mode is read mode
• When you open a file in read mode, the given file must
exist in the folder, otherwise Python will raise
FileNotFoundError
FILE ACCESS MODES
File must exist already, otherwise Python
‘r’ Read Only raises I/O errors
Syntax: <fileHandle>.close()
Example: f.close()
READING FROM FILES
ﷺread()
ﷺreadline()
ﷺreadlines()
CREATING A TEXT FILE
1
Open any text editor,
and type any content
2 3
Copy the path from Save your file in the
where your python is path which is copied
installed with .txt extension
read()
Syntax: <fileHandle>.read([n])
Code Snippet:
Output
f.read(n)
Reading a file’s first 30 bytes and printing it.
Code Snippet
Output
f.read(n)
Reading n bytes and then reading some
more bytes from the last position read.
Code Snippet
Output
readline()
Syntax:
<fileHandle>.readline([n])
• Reads a line of input
Code Snippet:
Output:
Reading a file’s first three lines – line by line
Code Snippet:
Output:
Reading a file’s first three lines – line by line
Code Snippet:
Output:
Reading a file using readline(n)
Code Snippet:
Output:
Reading a complete file line by line
Output:
Code Snippet:
Reading a file line by line using for loop
Output:
Code Snippet:
Displaying the size of a file after removing EOL
characters, white spaces & blank lines
Code Snippet: Output:
readlines()
Syntax: <fileHandle>.readlines()
Code Snippet
Output:
Program to display the size of a file in bytes
Code Snippet:
Output:
Program to display the number of lines in a file
Code Snippet:
Output:
WRITING ONTO FILES
ﷺwrite()
ﷺwritelines()
Code Snippet
Output
Create a text file to hold some data
Code Snippet
Output
Create a text file to hold student names
Code Snippet :
Code Snippet :
Text File :
Input :
Create a file with some names separated by newline characters
without using write() function
Code Snippet :
Input :
Text File :
Program to add two more students details to the file Marks.txt
created earlier
Code Snippet :
Input : Text File :
Program to display the contents of file ‘Marks.txt’ which is
created earlier
OR
Program to read a text file line by line and display each
word separated by a ‘#’