☰
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


 ☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 2 : Data (Input) : Python File Object

Python File Object

Subscribe Contact


Contents

Overview

As introduced on the previous page, files are one of the core elements of working with a computer for users and programmers. Nearly all applications create or interact with files that are stored on a device, that is, computers, servers, cloud devices, mobile devices, tablets, hard drives, USB drives, etc. Files are the primary tools that we use to store persistent data that we want to access again and again. As a programmer, it is critical to become very familiar with files, and how files are created, manipulated, and stored. This includes developing an understanding of how operating systems handle files and storage. Python provides a full suite of tools for file handling and we will explore in this chapter.

The Python File Object

In Python, a file object is a crucial concept that serves as a gateway between your Python code and various files on your computer. When you're working with files - whether reading data from them, writing data to them, or both - you interact with these files through what Python calls a 'file object'. Think of a file object as a middleman; it sits between your Python program and a file stored on your computer, facilitating the process of reading from or writing to that file.

Opening a File

To interact with a file in our Python code, we must first open the file. Opening a file using Python code involves establishing a file object variable and assigning the result of the open() function to that variable. Inside of the open() function we specify the file we want to open and the mode (the type of access (read, write) we want to the file) to use to open it. You can find a full list of file access modes here.

The general form of the open() function is as follows:

file_var = open([r][Path]file_name [, file_access_mode])

Code Details:

Example 1

Let's say I have a file in my Documents directory called Sample.txt that I want to open to read in my Python code. If I open that file in a plain text editor it looks like this (notice the absolute path in the title bar of the screenshot window):

To open this file in Python I can write the following ...

my_file = open(r"C:\Users\John\Documents\Sample.txt", "r")

... and, if the file exists at that location, then the variable my_file will contain an object reference to the file and it will be opened with mode "r", which means read-only access. This means I'll be able to read the file but I am not able to write to the file. At this point, nothing has happened to the file itself yet.

Reading from a File

Once I have opened the file using the open() function, I can start reading from the file. I have several options for reading from the file, I can read it all at once into a variable or I can read it one line at a time (sequentially). For this first example, let's read it all at once and then print the contents on our screen.

my_file = open(r"C:\Users\John\Documents\Sample.txt", "r")
file_contents = my_file.read()
print(file_contents)

Output:

This is the first line of text in my file.
This is the second line of text in my file.
This is the third line of text in my file.
This is the fourth line of text in my file.
This is the fifth line of text in my file.

Now that I have read the contents of the file into a variable I can use that variable to work with that content as needed.

Closing a File

It is important to close external resources, such as files, as soon as we are finished with them. Not closing resources can cause conflicts and unexpected results otherwise. To close a file simply use the file method close(), like this...

my_file.close()

So, if we combine all of the code so far we have this ...

my_file = open(r"C:\Users\John\Documents\Sample.txt", "r")
file_contents = my_file.read()
my_file.close()
print(file_contents)

Notice where I placed the my_file.close() statement, on Line 3 right after I captured the contents of the file into my file_contents variable. I no longer needed the file because the file_contents variable has all of it, so I close the file right away. I can then work with the contents using my variable after that, like printing it as shown in this code.

Writing to a File

Next, to write (add content) to a file we first need to determine if the file we intend to write to will be a new file or if it is an existing file. This is an important distinction because it will determine which access mode we will use. The two modes we can use to write to a file are ...

File Access Mode Description
w
Opens the specified file for writing only. If the file exists already at the location specified, the existing file is overwritten. If the file does not exist already, the file is created with the name specified.
a
Opens the specified file for appending. If the file exists, the file pointer is positioned at the end of the file and the file is set to append mode, that is, any new data written to the file will be appended (added) to the end of the file. If the specified file does not already exist, then the file is created using the file name specified, the file pointer will be at the beginning of the empty file and the file will be set for writing.

Examples of File Access Mode: "w":

Continuing with our Sample.txt file from above, since it is an existing file with multiple lines of content, the following code example will open the file for writing. Subsequently, when we write data to it, its content will be overwritten.

my_file = open(r"C:\Users\John\Documents\Sample.txt", "w")

If we use the same code line with write mode, however with a file name that does not exist, that file will be created first, and then when we write data to it the data will be added beginning on the first line of the file.

my_file = open(r"C:\Users\John\Documents\NewFile.txt", "w")

Example of File Access Mode: "a":

If we consider our Sample.txt file again, however this time if we intend to write content to it without overwriting it, that is we want to add data to it without affecting the existing content, then we change the access mode to append "a".

my_file = open(r"C:\Users\John\Documents\Sample.txt", "a")

Full Code Examples::

Example 1::

my_file = open(r"C:\Users\John\Documents\Sample.txt", "w")
my_file.write("This is a line added to my Sample.txt file by my Python program.")
my_file.close()
Result: Notice in the screenshot below of our Sample.txt file there is only one line in the file now, the line from our Python program above. Since this file was an existing file and we used the write "w" access mode, the original file contents were overwritten by the Python program my_file.write() statement.


Example 2::

my_file = open(r"C:\Users\John\Documents\NewFile.txt", "w")
my_file.write("This is a line added to my NewFile.txt file by my Python program.")
my_file.write("This is another line added to my NewFile.txt file by my Python program.")
my_file.close()
Result: Notice in the screenshot below that in this code example, we created a new file and wrote two lines of text to it with the two write() statements.


Example 3::

my_file = open(r"C:\Users\John\Documents\Sample.txt", "a")
my_file.write("This is a line appended to my Sample.txt file by my Python program.\n")
my_file.write("This is another line appended to my Sample.txt file by my Python program.\n")
my_file.write("This is another line appended to my Sample.txt file by my Python program.\n")
my_file.write("This is another line appended to my Sample.txt file by my Python program.\n")
my_file.write("This is another line appended to my Sample.txt file by my Python program.\n")
my_file.write("This is yet another line appended to my Sample.txt file by my Python program.\n")
my_file.close()
Result: In the screenshot below .



Conclusion



 





© 2023 John Gordon
Cascade Street Publishing, LLC