READ FILES



Python - Read Files


Open a File on the Server :


Assume we have the following file, located in the same folder as Python:


freedomfile.py

WELCOME TO FREEDOM TUTORIALS
FREEDOM TUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.
IT LENDS INFORMATION ABOUT ALL THE COURSES BETTER ENOUGH.
    




To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:


f = open("freedomfile.py", "r")
print(f.read())

======o/p=======

WELCOME TO FREEDOM TUTORIALS
FREEDOM TUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.
IT LENDS INFORMATION ABOUT ALL THE COURSES BETTER ENOUGH.
    

Read Only Parts of the File :


By default the read() method returns the whole text, but you can also specify how many characters you want to return:


Return the 5 first characters of the file:

f = open("freedomfile.py", "r")
print(f.read(15))

========o/p========

WELCOME TO FREE


Read Lines :


We can return one line by using the readline() method.


Read one line of the file :

f = open("freedomfile.py", "r")
print(f.readline())


========o/p========

WELCOME TO FREEDOMTUTORIALS


By calling readline() two times, you can read the two first lines:


Read two lines of the file:

f = open("freedomfile", "r")
print(f.readline())
print(f.readline())


========o/p=======

WELCOME TO FREEDOMTUTORIALS

FREEDOMTUTORIALS IS THE BEST TUTORIALS AMONG THE BEST ONES.


Close Files :


It is a good always to close the file when we are done with it.


f = open("freedomfile.py", "r")
print(f.readline())
f.close()


========o/p=========

WELCOME TO FREEDOMTUTORIALS


Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.



RegEx SETS

Python - RegEx SETS

posted on 2019-11-12 23:06:24 - Python Tutorials


RegEx_Functions

Python - RegEx_Functions

posted on 2019-11-09 06:07:29 - Python Tutorials


RegEx_Sets

Python - RegEx_Sets

posted on 2019-11-09 05:30:54 - Python Tutorials


Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials