How to do File Import in Python Notes
My notes on how to do File Import in Python notes taken during my Python Dev Bootcamp.
Python File import
- .read()
- Returns everything in the text file
- Once everything has been returned, the cursor position is at the bottom. As such, if you re-run read(), it will not return anything as it is already at the end of the file.
- You need to reset the cursor’s position to read the documents from the beginning
- .seek(0)
- Resets the cursor’s position to the beginning
- .readlines()
- Displays texts in the file in their own lines i.e. its own separate object as a list
- Advantages:
- As it is displayed as a list
- You can loop through the list
- You can use it as an index
- Python File Import Best Practices
- If you open a file, you should close the file
- .close()
- OR (better option)
- with open(‘myfile2.txt’) as my_new_file:
- contents = my_new_file.read()
- If you open a file, you should close the file
- Write/Overwrite Files During File Import
- Mode
- R
- Read only
- W
- Write only (will overwrite files or create new)
- A
- Will append only
- R+
- Reading and write
- W+
- Overwrites existing files or creates a new file
- R
- Mode
The above examples are pretty basic and cover notes from m Python Bootcamp lessons and are not comprehensive. As I skill-up, I will add additional notes for my personal references as a diary.
Future Notes on Python Development
I have also covered notes from other topics during my dev bootcamp and should be accessible from the Programming section. Notes include, use of Lists, Dictionaries, String Formatting for Printing with Python. Finally, you can also look at the start of my journey into python with Learn to Code in Python article. I am going to talk about Tuples, Sets, Booleans, For Loops & While Loops, Python Inheritance, and Comparison Operators (IF ELSE) in my upcoming posts. In addition to the Python notes, I will start taking javascript classes as well and hope to document my journey and post learning javascript notes.