Skip to content

Commit f9926f7

Browse files
committed
started open() function
1 parent 2940c92 commit f9926f7

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

FileInputAndOutput/lesson_plan.txt

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,10 @@ path. While if I am in the Trump folder, .\Documents\nuclear_launch_codes.txt
7171
is the relative path. We can try this out in the windows command line.
7272

7373
Show graphic/example to compare and contrast
74-
. (dot) for this directory
75-
.. (dot-dot) for parent folder
74+
There are two shortcuts to represent this directory and the parent folder
75+
. (dot) for this directory
76+
77+
.. (dot-dot) for parent folder
7678

7779
### Creating New Folders
7880
Use **os.makedirs(path)** to create a folder
@@ -122,7 +124,7 @@ is used
122124
>> os.path.split(path)
123125
('C:\\Windows\\System32', 'calc.exe')
124126
```
125-
# Finding File Sizes and Folder contents
127+
### Finding File Sizes and Folder contents
126128
**os.path.getsize(path)** returns the size in bytes of the file
127129
**os.listdir(path)** returns a list of strings for each file in the path
128130
```python
@@ -132,6 +134,33 @@ is used
132134
totalSize = totalSize + os.path.getsize(os.path.join('.', filename))
133135
>> print(totalSize)
134136
```
137+
138+
### Checking path Validity
139+
Python will crash if you provide a path that does not exist. Luckily, the
140+
os.path modules has some functions for us to prevent that.
141+
142+
**os.path.exists(path)** - returns True if the file or folder exists and returns
143+
False if it doesn't.
144+
**os.path.isfile(path)** - returns True if the path points to a file and returns
145+
False if it doesn't.
146+
**os.path.isdir(path)** - returns True if the path points to a folder and
147+
returns False if it doesn't.
148+
149+
## Reading and Writing Files
150+
We need to be comfortable with all the functions above so we can tell Python
151+
exactly the location of the files we want to read and write. The files we will
152+
be working on are *plaintext files*, which contain only normal human-readable
153+
text. Examples of plaintext files are files that end with .txt, or .py. We
154+
will **not** be working with *binary files* which are only computer readable
155+
files. If we tried to open a binary file to read, we will get garbled text.
156+
157+
We will be using three functions to read plain text files,
158+
**open()** - returns a *File* object
159+
**read()** or **write()** - reads from or writes to the file
160+
**close()** - closes the *File* object which allows Python to save the file
161+
162+
### Opening Files with the open() Function
163+
135164

136165
os.path.abspath()
137166
os.path.basename()

0 commit comments

Comments
 (0)