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

Chapter 5.1 Text File Handling

The document provides a comprehensive overview of file handling in programming, including definitions of key terms, types of files, and various commands for opening, reading, writing, seeking, flushing, and closing files. It also discusses the importance of closing files and introduces the 'with' statement for file manipulation. Additionally, shortcuts for reading files and standard input/output/error streams are covered.

Uploaded by

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

Chapter 5.1 Text File Handling

The document provides a comprehensive overview of file handling in programming, including definitions of key terms, types of files, and various commands for opening, reading, writing, seeking, flushing, and closing files. It also discusses the importance of closing files and introduces the 'with' statement for file manipulation. Additionally, shortcuts for reading files and standard input/output/error streams are covered.

Uploaded by

Aarna Bhura
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1. Definitions:...........................................................................................................

2
1. Types of files:....................................................................................................... 2
2.1 Text Files........................................................................................................ 2
2.2 Binary File...................................................................................................... 2
2.3 Comma Separated Values (CSV)....................................................................2
2. Open Command................................................................................................... 2
2. Read Commands.................................................................................................. 4
4. Write Commands.................................................................................................. 4
5. Seek Command.................................................................................................... 4
6. Flush Command - fd.flush().................................................................................. 4
7. Close Command - fd.close()................................................................................. 4
8. With command syntax and usage........................................................................5
9. Short Cuts to reading files.................................................................................... 5
File Handling

1. Definitions:
1 Relative and Absolute Paths.
i. Relative path – The file name mentions the path relative to
the current working directory.
ii. Absolute Path – The file name mentions the complete path
from the top-level directory. The file name starts with the
drive name. (C: , D:)
2 File Object, File Handler , File Descriptor – A file object is a
reference to a file on disk. It opens and makes it available for a
number different task.
3 Offset - The position where the file reader is currently pointing.

2. Types of files:
2.1 Text Files
Stores information in the form of a stream of ASCII Code.

2.2 Binary File


A binary file stores the information in the form of a stream of bytes.

2.3 Comma Separated Values (CSV)


Comma separated values are stored in file.

3. Open Command
fd = open (file_name,mode)
open() Parameters

 file - path-like object (representing a file system path)


- The file_name should have \\ in file name.
fd= open(“C:\\Prog\\text1.txt” , “r”)
- In case the file name is mentioned with \\ add a ‘r’ in front of file
name.
fd= open(r“C:\Prog\text1.txt” , “r”)
- IN case only file name is mentioned, it is opened at the location
where python is run.
 mode (optional) - mode while opening a file. If not provided, it defaults
to 'r' (open for reading in text mode). Available file modes are:
Mod Description
e
'r' Open a file for reading. (default)
'w' Open a file for writing.
Creates a new file if it does not exist or truncates the file if it exists.
'x' Open a file for exclusive creation.
If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it.
Creates a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)

Return Value from open()

The open() function returns a file object which can used to read, write
and modify the file.
If the file is not found, it raises the FileNotFoundError exception.
4. Read Commands
4 read() : This function reads the entire file and returns a string
5 read(n) : This function reads n bytes from the file and returns a
string.
6 readline() : This function reads lines from that file and returns
as a string. It will fetch the line n, if it is been called nth time.
To remove the ‘\n’ at the end of the line call:-
line = fh.readline()
line = line.rstrip(‘\n’)
7 readlines() : This function returns a list where each element is
single line of that file.

Returns an empty string when end of file is encountered. There is


no error in the read command when the file ends.

5. Write Commands
a. write() : This function writes a fixed sequence of characters
to a file. To go to the next line after writing put a ‘/n’ at the
end of the write string.
b. writelines() : This function writes a list of string.

6. Tell Command
fd.tell()
It returns the current offset of the pointer in the file.

7. Seek Command
fd.seek(offset, reference)
- Offset : no of bytes.
- Reference – 0: Beginning of the file.
1: Current position of the file.
2: End of the file.

Negative offset does not work with text files.

8. Flush Command - fd.flush()


Flushes the write buffer in the file.

9. Close Command - fd.close()


Closes the file.
10. Why file closing is important?
1. It is a good programming practice.
2. To ensure that data buffer has been written on the file.
3. Sometimes the operating system has restrictions on the
number of opened files at any time. Thus, you must close your
files when its work is done.
4. To make sure operating system does not get stuck and the
blocked memory is freed.
5. With command syntax and usage.
Syntax – with open (<file_name> , <filemode>) as <filehandle> :
<File manipulation statements>
Example:
With open(“Sample.txt”, “r”) as fd :
X=fd.read()
print(X)

- With statement closes the file by itself.


- All the commands related to the file as to be present in the with
block.

6. Short Cuts to reading files


1. X = open(“C:\\Prog\\text1.txt” , “r”).read()
Print (X)
2. fd = open(“C:\\Prog\\text1.txt” , “r”)
for line in fd
print(line)

in both the cases contents of the file would be printed.


7. Standard Input , Ouput and Error Streams.
a. Standard input device (stdin) – reads from the keyboard.
b. Standard output device (stdout) – prints to the dispay.
c. Standard error device (stderr) – Same ass stdout but generally
displays error.
Example:

import sys

fd = open(r”E:\work.txt”)

line1= fd.readline()

line2= fd.readline()

sys.stdout.write(line) - same as print(line)

sys.stdout.write(line) - same as print(line)

sys.stderr.write(“No Errors Occurred\n”)

You might also like