Skip to content

Commit 71ca485

Browse files
committed
use Path from pathlib
1 parent f03fd00 commit 71ca485

File tree

4 files changed

+27
-8
lines changed

4 files changed

+27
-8
lines changed

07-files/files4.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
11

2-
# You can also use the `readlines()` method to iterate over the lines of a file
2+
# Use the Path class from pathlib to create OS-agnostic file paths
3+
from pathlib import Path
34

4-
filepath = r'07-files/shopping_list.csv'
5+
# Create a Path subclass object that starts in this directory
6+
files_dir = Path('./07-files')
57

6-
print(f"\nContents of {filepath}:\n")
8+
# Append the name of the file we want to work with using slash notation
9+
filepath = files_dir / 'shopping_list.csv'
710

11+
print(f"\nContents of {filepath.absolute()}:\n")
12+
13+
# Use `readlines()` to iterate over the lines of the file
814
with open(filepath) as file:
915
for line in file.readlines():
1016
print(line, end='')
17+
18+
19+
20+
# Pathlib can do all sorts of things -- make directories, check if a path is
21+
# a file or a directory, list the contents of directories, and more:
22+
# https://rednafi.github.io/digressions/python/2020/04/13/python-pathlib.html

07-files/files5.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11

2-
# This time let's open a file for appending.
32

4-
# Define file path with an "r"-string
5-
filepath = r'07-files/soliloquy.txt'
3+
# This time let's append to a file. By default files are opened for reading,
4+
# in "text" mode. More: https://riptutorial.com/python/example/978/file-modes
5+
6+
from pathlib import Path
7+
files_dir = Path('./07-files')
8+
filepath = files_dir / 'soliloquy.txt'
69

710
new_lines = ["To sleep, perchance to dream; ay, there's the rub;",
811
"For in that sleep of death what dreams may come",
912
"When we have shuffled off this mortal coil,",
1013
"Must give us pause."]
1114

12-
# Open for reading
15+
# Open for reading; note the variable name given to the file object
1316
with open(filepath, mode='r') as reader:
1417

1518
# Enumerate over the file, but do nothing ("pass") with its contents
@@ -37,4 +40,4 @@
3740
for line_num, line in enumerate(reader, start=1):
3841
print(line_num, line, end='')
3942

40-
print(f"\nWrote {len(new_lines)} extra lines.")
43+
print(f"\nWrote {len(new_lines)} extra lines.\n")

07-files/files6.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
# CSVs

07-files/files7.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
# Compare CSVs

0 commit comments

Comments
 (0)