Data File Handling Text File
What is text File?
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.
Read:
1. read()
2. readline()
3. readlines()
Write:
1. Write()
2. Writelines()
Working with text file:
Reading from text files:
1. read()
2. readline()
3. readlines()
S.No | Method | Syntax | Description |
1. | read() | <filehandle>.read([n]) | Read at most n bytes; if no n is specified,reads the entire file. Returns the read bytes in the form of a string. For example: 1 f1=open("test.txt") a=f1.read(15) print(a) Output: >>>12345678Python >>> f1.close() For example: 2 f1=open("test.txt") a=f1.read() print(a) f1.close() Output: >>>12345678Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small- and large-scale projects |
2 | readline() | <filehandle>.readline([n]) | Reads a line of input; if n is, specified reads at most n bytes. Returns the read bytes in the form of a string ending with in(line)character or returning a blank string if no more bytes are left reading in the file. For example 1: f1=open("test.txt") a=f1.readline() print(a) f1.close() Output: >>>Python is a high-level, general-purpose programming language.12345 >>> For example 2: f1=open("test.txt") a=f1.readline(11) print(a) f1.close() Output: >>>Python is a >>> |
3 | readlines() | <file_handle>.readlines()
| Reads all lines and returns them in a list For example: f1=open("test.txt") a=f1.readlines() print(a) f1.close() Output: ['Python is a high-level, general-purpose programming language.12345\n', 'Its design philosophy emphasizes code readability with the use of significant indentation.\n', 'Its language constructs and object-oriented approach aim to help programmers write clear,\n', 'logical code for small- and large-scale projects'] |
Writing onto text file:
After working with file reading functions, let us talk about the writing functions for data file available in python.
S.No. | Name | SYNTAX | Description | |
1. | write() | <filehandle>.write(str1) | Write string str1 to file referenced by <filehandle> For example 1: f1=open("test.txt",'w') a=input("Enter the name") # direct string f1.write(a) f1.close() Output: Enter the name For example2: f1=open("test.txt",'w') a=input("Enter the name") f1.write(a) f1.close() Output: Athishtlakshmi | |
2. | writelines() | <filehandle>.writelines(L) | Writes all strings in list L as lines to file referenced by <filehandle> For example 1: f1=open("test.txt",'w') l1=[] for i in range(5): a=input("Enter the name") f1.writelines(a) f1.close() Output: Interactive mode: Enter the name gajanani Enter the name ajitha Enter the name varun Enter the namelakshmi Enter the nameathishta >>> Notepad: gajanani ajitha varunlakshmiathishta
|
file 1=open(“Employees.txt”,”w”)
lst=[]
for I in range(3);
name=input(“Enter the name of the employee: ”)
Lst.append(name+’\n’)
file1.writelines(lst)
file1.close()
print(“Data is written into the file”)
#Write a program to get roll numbers,names and marks of the students of a class
#(get from user) and store these details in a file called "mark.txt"
a=int(input("Enter the number of students"))
f=open("mark.txt","w")
for i in range(a):
rollno=input("Enter your Roll Number")
name=input("Enter your Name")
marks=input("Enter your mark")
rec=str(rollno)+","+name+","+str(marks)+'\n'
f.write(rec)
f.close()
Appending a file:
When you open a file in ”w” or write mode,python overwrite an exiting file or create a
non-existing file.That means,for an existing file with the same name, the earlier data get lost.if,however,you want to write into the file with the same name.
That means, in python,writing in files can take place in following forms:
1. In an existing file, while retaining its content
i. If the file has been opened in append mode (‘a’) to retain the old contents.
ii. If the file has been open in ‘r+’ or ‘a+’ modes to facilitate reading as well as writing.
2. to create a new file or to write on an existing file after truncating /overwriting its old content
i. If the file has been opened in write-only mode (‘w’)
ii. If the file has been open in ‘w+’ mode to facilitate writing as well as reading.
3. Make sure to use close() function on file-object after you have finished writing as sometime,the content remains in memory buffer and to force-write the content on file and closing the link of file handle from file, close() is used.
The flush function:
The flush () function force the writing of data on disc still pending in output buffer.
Syntax
<file_object>.flush()
Removing white space after reading from file
If you want to remove any of these trailing and leading whitespaces,you can use strip() functions [rstrip(),lstrip(), and strip()]
The strip() removes the given character from both ends.
The rstrip() removes the given character from trailing end., right end
The lstrip() removes the given character from leading end I.e.,left end
To understand this,consider the following example
1. Removing EOL ‘\n’ character from the line read from the file
f=file(“poem.txt”,’r’)
line=f.readline()
line=line.rstrip(‘\n’)
2. Removing the leading whilespaces from the line read from the file
line=file(“poem.txt”,’r’)
line=line.lstrip()
Significance of file pointer in file handling:
Every files maintains a file pointer which tells the current position in the file where writing or reading will take place.
Whenever you read sometime from the file or write onto a file,then these two things happen involving file-pointer.
1. this operation takes place at the position of file pointer and
2. File pointer advances by the specified number of bytes.
1.f=open(“Mark.txt”,”r”)
Will open the file and place the file pointer at the beginning of the file.
| 2 | N | O | 321 | Erw | F | D | K | L |
2.ch=f.read(1)
Will read 1 bytes from the file from the position the file -pointer is currently at; and the file pointer advances by one byte. That is, now the ch will hold ‘p’ and the file pointer will be at next bytes holding values ‘2’.
p |
| N | O | 321 | Erw | F | D | K | L |
Will read 2 bytes from the file from the position the file -pointer is currently at; and the file pointer advances by one byte. That is, now the ch will hold ‘p’ and the file pointer will be at next bytes holding values ‘O’.
p | 2 | N | O | 321 | Erw | F | D | K | L |
Standard input device (stdin) read from the keyboard
Standard output device (stdout) prints to the display and can be redirected as standard input
Standard error device (stderr) same as stdout but normally only for error
Module Name: sys
Syntax:
import sys
sys.stdin.read()
sys.stdout.write()
sys.stderr.write()
For example
import sys
f=open("test.txt")
line1=f.readline()
line2=f.readline()
sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write("No Errors occurred\n")
Absolute and relative paths:
Absolute path
Full name of the file or directory or folders consists of path\primaryname.extention
Path is a sequences of directory names which give the hierarchy to access a particular directory or file name.
For example:
E:\PROJECT\a\test.txt
D:\SALES
\ --> Refers the root path
The full name of the file or a directory is also called pathname
Relative path
the paths relative to current working directory.
The symbol of .(one dot) and ..(two dots) can be used relative path and path name.
For example
.\Two.doc current folder
..\two.txt parent folder
..\project\report.dat working folder
0 Comments