File tree 3 files changed +54
-1
lines changed
3 files changed +54
-1
lines changed Original file line number Diff line number Diff line change
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 )
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change @@ -12,7 +12,7 @@ def wc(file_):
12
12
char_counter = 0
13
13
for line in data .splitlines ():
14
14
# print(ch)
15
- print (line )
15
+ # print(line)
16
16
line_counter = line_counter + 1
17
17
# print(char_counter)
18
18
for word in line .split ():
You can’t perform that action at this time.
0 commit comments