Skip to content

Commit babd07e

Browse files
bite 100
1 parent f1a1dfc commit babd07e

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

100/tail.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
def tail(filepath, n):
2+
"""Similate Unix' tail -n, read in filepath, parse it into a list,
3+
strip newlines and return a list of the last n lines"""
4+
file_ = str(filepath)
5+
for line in file_.split(" "):
6+
with open(file_, "r") as tempfile:
7+
data = tempfile.read()
8+
9+
dat = list()
10+
for line in data.splitlines():
11+
dat.append(line)
12+
13+
total_line = len(dat)
14+
# print(dat)
15+
dat = dat[total_line-n:total_line]
16+
# print(dat)
17+
return dat
18+
19+
20+
tail("/home/bora/0WORKYR3/_pybites/bitesofpy/101/driving.py",2)

100/test_tail.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import pytest
2+
3+
from tail import tail
4+
5+
content = b"""Hello world!
6+
We hope that you are learning a lot of Python.
7+
Have fun with our Bites of Py.
8+
Keep calm and code in Python!
9+
Become a PyBites ninja!"""
10+
11+
12+
# https://docs.pytest.org/en/latest/tmpdir.html#the-tmpdir-factory-fixture
13+
14+
@pytest.fixture
15+
def my_file(tmp_path):
16+
f = tmp_path / "some_file.txt"
17+
f.write_bytes(content)
18+
return f
19+
20+
21+
def test_tail_various_args(my_file):
22+
assert tail(my_file.resolve(), 1) == ['Become a PyBites ninja!']
23+
assert tail(my_file.resolve(), 2) == ['Keep calm and code in Python!',
24+
'Become a PyBites ninja!']
25+
26+
27+
def test_tail_arg_gt_num_lines_files(my_file):
28+
# n of > file length basically gets the whole file, but need to do some
29+
# byte to str conversion and strip off last line's newline char
30+
actual = tail(my_file.resolve(), 10)
31+
expected = [line.decode("utf-8")
32+
for line in content.splitlines()]
33+
assert actual == expected

96/wc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def wc(file_):
1212
char_counter = 0
1313
for line in data.splitlines():
1414
# print(ch)
15-
print(line)
15+
# print(line)
1616
line_counter = line_counter+1
1717
# print(char_counter)
1818
for word in line.split():

0 commit comments

Comments
 (0)