What is a file?
- Every file in the computer is just a series of bytes, which is arranged one after the other.
- All the bytes are of 8 bits, Hence each byte is a number between 0 and 255.
- As we discussed in the above point, every file consists of bytes. So, each file can be considered as a binary file.
- But if the file contains bytes for only text (characters, numbers, and other symbols) that everyone uses for general purpose, then the file can be considered as a text file.
Types of Files
Binary Files – A binary file is just a file that contains information in the same format in which the
information is held in memory.
Text Files - Text files can be considered as a subset of binary files. That is used to store human-readable characters as RTF (rich text file) or plain text document. Text files are of two types:-
- Plain text files (.txt)
- Rich text files (.rtf)
CSV Files (Comma Separated Values) – A Comma Separated Values (CSV) file is a simple text file that contains data as comma-separated values. CSV files can be used for exporting and importing the data between different applications. For example, we can transfer data between databases and Python Pandas using CSV.
Absolute and Relative Path of Files
Absolute Path – It is a full path of the file from the root directory.
Ex : - C:\Users\Tanmay\Desktop\Delete\file handling.txt
Relative Path – It is the path of the file from the current working directory.
Ex: -If I am on Desktop then the relative Path for file “file handling.txt” is .\Delete\file handling.txt
Operation on files in python
1.Opening a file– open() function
2.Read/Write file–
– Read Functions – read() , readline(), readlines()
– Write Functions – write() , writelines()
3.Close the File – close() Function
4.Remove the file – remove() Function of OS Module
2.Read/Write file–
– Read Functions – read() , readline(), readlines()
– Write Functions – write() , writelines()
3.Close the File – close() Function
4.Remove the file – remove() Function of OS Module
Read the contents of an existing file
1.Open the file–
file_object = open(“read_sample.txt”, ’r’) # Relative Path
file_object = open(“C:\Desktop\Notes\sample.txt”) #Absolute Path
2.Reading the file–
rf = file_object.read()
print(rf)
3.Closing the file–
file_object.close()
No comments:
Post a Comment