ob-vaults/Phoenix/Python/Read Text File in Python.md
2024-09-12 17:54:01 +03:30

2.8 KiB
Raw Blame History

status: #doc Tags: #python #programming links:python python/text Date: 2023-04-30


Read Text File in Python

TL;DR

reading file and make list of lines of it

with open('readme.txt') as f:
    lines = f.readlines()

using open function

  • first you must open a file with open function like this
f = open("demofile.txt", "r")

OR

with open('readme.txt', "r") as f:

open() return a file object that must go to file object in here we use {f} for storage , argument are

  • first arg is file path
  • second arg is open mode

open modes

open function have different modes (second arg)that can be seen here but 4 most important are

  • "r" - Read - Default value. Opens a file for reading, error if the file does not exist
  • "a" - Append - Opens a file for appending, creates the file if it does not exist
  • "w" - Write - Opens a file for writing, creates the file if it does not exist
  • "x" - Create - Creates the specified file, returns an error if the file exist

file object usage

we can use file object with its methods most common in use are

usage example :

f = open("demofile.txt", "r")  
print(f.read())

 close() method

The file that you open will remain open until you close it using the close() method.

Its important to close the file that is no longer in use for the following reasons:

  • First, when you open a file in your script, the file system usually locks it down so no other programs or scripts can use it until you close it.
  • Second, your file system has a limited number of file descriptors that you can create before it runs out of them. Although this number might be high, its possible to open a lot of files and deplete your file system resources.
  • Third, leaving many files open may lead to race conditions which occur when multiple processes attempt to modify one file at the same time and can cause all kinds of unexpected behaviors.

The following shows how to call the close() method to close the file:

f.close()

To close the file automatically without calling the close() method, you use the with statement like this:

with open(path_to_file) as f:
	contents = f.readlines()

References

https://www.pythontutorial.net/python-basics/python-read-text-file/