21: Text File
Text File
All the work we have done so far, our data stored in main memory that is volatile and it is removed just after ending the execution but in real life, we have to store the data permanently that should be available even after shutting down the computer. Secondary storage of computers like hard disks or solid-state drives can store such data. These devices store data in the form of Files. We discuss how files create, open, update or delete using Python code.
- Two types of files
- Text Files
- These files contain only string data
- Text files may have different extensions by the data storage and opening mechanism remains the same.
- These files can be open with any text editor.
- Binary Files:Â
- These files store numeric data.
- These files have different extensions and every extension has its own storage and open mechanism.
- Every binary file opens with its own software like images always open in some image viewer or image editor, video files open in a media player or video editor.
- We will work on simple text files in this lecture.
- Python has built-in library functions to perform operations on text files.
- Python can also work on binary files but they require extra libraries which are required to be installed explicitly.
- There are four basic operations on files.
- Create/Write: Creating and putting content in a new file on secondary storage.
- Read: Getting content from file.
- Updating: Changing content of the file.
- Deleting: Removing file from secondary store.
- Before working on files, we must have some initial understanding of the File System.
- According to the OS (Operating System), secondary storage is an input and output device.
- Every OS (Windows, Linux, iOS) has its own file system.
- Windows virtually distributes the storage device (HDD or SSD) into parts called logical drives.
- Windows name them C, D, E and so on (Why not from A).
- Every logical drive is called root directory.
Figure 1: Logical Drives in my Computer
- Every logical drive may contain files and sub directories in it.
- These directories are called folders.
Figure 2: Files and Folders in C Drive
- Files contain data while directories (we will use this word for the rest of the lecture) contain files and other sub-directories.
- When we access a file for any operation, we must have its address.
- The address of the file is also called path.
- For example, in my D drive, I have created a directory of “Courses” and inside “Courses” I created another directory “Python”.
- In the “Python” directory, I created my file “Text File.pdf”.
- Now the address of my file will be “d:/Courses/Python/Text File.pdf”.
- “D” is the root directory, “Courses” and “Python” are sub-directories and “Text File.pdf” is the file name.
- The file path that starts from the root directory name (D in my case) is called absolute path.
- Normally, using absolute path is good but it can be very long due complex directory structure so we can use it in shortened form called relative path.
- We will use relative paths in this lecture.
- Windows has no issue with small or capital names but Linux considers them. So, if you are working on Linux then take care of the case of directory and file name.
file = open ("my file.txt", "w")file.write ("Hello, World!")
Code 1: Opening a file For Writing
- First, we open the file by providing its relative path.
- We did not provide any directory name in path because my code and the target “my file.txt” are both in the same directory.
- We also provide “w”, the second parameter to open function.
- The w will inform the open function to open this file in write mode or we want to open the file for writing.
- The open function is very intelligent. It tries to find the file in the given directory and if the file does not exist then it will create an empty file.
- After creation or finding the file, it returns its reference.
- References will be discussed in OOP lectures.
- Then call the write function and provide a string that should be written to file.
- This is similar to the print function. The difference is that print writes on the computer screen and write, writes into the file on storage. Both are using output devices.
- You can also find that the file “my file.txt” is now created in your directory. The same directory where your Python code file exists.
- You can also open this file with any text editor like Notepad, Notepad++ or Visual Studio Code.
Figure 3: Opening newly created File in Notepad
- You can see that your provided string is in the file.
- When data is written to file, then it permanently stores in storage and if you open it even after years, it will be available if not deleted by some user.
- It is good practice to close the file after the writing process.
file.close()
Code 2: Closing File
- Closing means its reference will be removed from memory and the file is free for any other operation.
- Similarly, we can use the read function to get all the content of a file by opening it in read mode.
e = open ("my file.txt", "r")content = file.read()
Code 3: Opening File in Read Mode
- “r” means read mode.
- open will return the reference of file object and then read function read all the content of file and return content.
- As we know that text files are strings so the variable content is string.
- The read function gets all the data of a file into a single string but we can also take data in the form of lines. For example, the following four lines are in my file.
Get up early in the morning
Go for a walk
Take breakfast
Ready for office
- Just open the file in Notepad and paste above lines in it and write file opening code in read mode to get reference.
- The readlines function will return the list of strings.
lines = file.readlines ()first_line = lines[0]
Code 4: Reading Lines will return a list of Strings
- first_line contains “Get up early in the morning”
- We can store data in files from users too.
product_data = []while True:  print ("Do you want to add a product? (yes/no) ")  response = input()  if response == "n":    break  product_id = input("Enter product ID: ")  product_name = input("Enter product name: ")  product_price = input("Enter product price: ")  product_record = f"{product_id},{product_name},{product_price}\n"  product_data.append(product_record)
Code 5 : Storing Product Data in File.
- For example, I want to store product data in a file like
1, “Head Phone”, 200
2, “Smart Watch”, 300
Here the 1 and 2 at start of the lines are product id, then head phone and smart watch is product name and finally there is product price.
- All the data entered by the user.
- Users are allowed to enter a number of records according to requirements.
- The above code helps you to enter the data from the user.
- First, we create an empty list of product_data. It will keep all the data which we want to store in file.
- Then run a while loop that allows the user to enter the data until he wants. If he enters no at any time, the loop will break.
- During the loop, every data element (ID, name and price) will be asked and placed in respective variables.
- Then we create a record on line 13. Record means data of a single product.
- This record appends to the product_data list which we create at the start of the program.
- After breaking the loop this code will store the product_data in products.txt file.
product_file = open("products.txt", "a")product_file.writelines(product_data)product_file.close()print ("File saved")
Code 6: Storing data into File
- Now run the program it will ask you to enter the data, if you enter y, it will ask for product information.
- When press n then it will save all the data into products.txt file.
Figure 4: Using Product Inventory Management System
- You can confirm data entry by opening the file in Notepad.
Figure 5: Watching Data in Notepad
- Consider that we open the file in “a” mode.








