| Opening a Text File | ||||||||||||||||||||||||||
use the open() function
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
# store its reference in the variable file1
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")
file modes
|
||||||||||||||||||||||||||
| Reading a Text File | ||||||||||||||||||||||||||
Reading from a File Using read()
.read() returns the read bytes in form of a stringreads n bytes if no n specified, reads the entire file File_object.read([n]) Reading a Text File Using readline()
.readline() reads a line of the file and returns in form of a stringfor specified n reads at most n bytes does not reads more than one line, even if n exceeds the length of the line File_object.readline([n]) Reading a Text File Using readlines()
.readlines() reads all the lines and returns them as each line a string
element in a list
File_object.readlines()'\n' is treated as a special character of two bytes |
||||||||||||||||||||||||||
| Writing a Text File | ||||||||||||||||||||||||||
|
Writing to a Text File Using write()
.write() inserts a string str1 in a single line in the text file
file = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
file.write(name)
# .write() does not add a newline
file.write("\n")
file.close()
Writing to a Text File Using writelines()
writelines() writes a list of string elements to the fileeach string is inserted in the text file individually used to insert multiple strings at a single time file1 = 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()
|
||||||||||||||||||||||||||
| Appending to a Text File | ||||||||||||||||||||||||||
use the append file mode
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
|
||||||||||||||||||||||||||
| Closing a Text File | ||||||||||||||||||||||||||
|
close() function closes the file frees the memory space acquired by the file # Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
|