Skip to content

Commit 6bb9d84

Browse files
committed
📝 Open files with contextmanager
1 parent 23b652d commit 6bb9d84

File tree

3 files changed

+8
-11
lines changed

3 files changed

+8
-11
lines changed

docs/modules/wc.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@ def words_occur():
66
# Prompt user for the name of the file to use.
77
file_name = input("Enter the name of the file: ")
88
# Open the file, read it and store its words in a list.
9-
f = open(file_name, "r")
10-
word_list = f.read().split()
11-
f.close()
9+
with open(file_name, "r") as f:
10+
word_list = f.read().split()
1211
# Count the number of occurrences of each word in the file.
1312
occurs_dict = {}
1413
for word in word_list:

docs/modules/wcargparse.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,17 @@ def words_occur():
1111
args = parser.parse_args()
1212
file_name = args.filename
1313
# Open the file, read it and store its words in a list.
14-
f = open(file_name, "r")
15-
word_list = f.read().split()
16-
f.close()
14+
with open(file_name, "r") as f:
15+
word_list = f.read().split()
1716
# Count the number of occurrences of each word in the file.
1817
occurs_dict = {}
1918
for word in word_list:
2019
# increment the occurrences count for this word
2120
occurs_dict[word] = occurs_dict.get(word, 0) + 1
2221
# Print out the results.
2322
print(
24-
"File %s has %d words (%d are unique)"
25-
% (file_name, len(word_list), len(occurs_dict))
23+
f"File {file_name} has {len(word_list)} words, "
24+
f"{len(occurs_dict)} are unique:"
2625
)
2726
print(occurs_dict)
2827

docs/modules/wcargv.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@ def words_occur():
88
# Prompt user for the name of the file to use.
99
file_name = sys.argv.pop()
1010
# Open the file, read it and store its words in a list.
11-
f = open(file_name, "r")
12-
word_list = f.read().split()
13-
f.close()
11+
with open(file_name, "r") as f:
12+
word_list = f.read().split()
1413
# Count the number of occurrences of each word in the file.
1514
occurs_dict = {}
1615
for word in word_list:

0 commit comments

Comments
 (0)