From 50de49fd7c81b535ac6559de2e68d30d67616ddf Mon Sep 17 00:00:00 2001 From: LaraibWaheed Date: Fri, 5 Aug 2022 16:33:50 +0500 Subject: [PATCH] File handling --- src/files/test_file_methods.py | 4 ++-- src/files/test_file_reading.py | 17 +++++++++++++++++ src/files/write_file.txt | 3 +++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/files/write_file.txt diff --git a/src/files/test_file_methods.py b/src/files/test_file_methods.py index e2684472..5dfc9f58 100644 --- a/src/files/test_file_methods.py +++ b/src/files/test_file_methods.py @@ -29,10 +29,10 @@ def test_file_methods(): # argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current # file position, and 2 uses the end of the file as the reference point. from_what can be omitted # and defaults to 0, using the beginning of the file as the reference point. - assert binary_file.seek(0) == 0 # Go to the 0th byte in the file + assert binary_file.seek(5) == 5 # Go to the 0th byte in the file assert binary_file.seek(6) == 6 # Go to the 6th byte in the file - assert binary_file.read(1) == '6' + assert binary_file.read(4) == '6789' # f.readline() reads a single line from the file; a newline character (\n) is left at the end # of the string, and is only omitted on the last line of the file if the file doesn’t end in a diff --git a/src/files/test_file_reading.py b/src/files/test_file_reading.py index 7a36a489..92e1736c 100644 --- a/src/files/test_file_reading.py +++ b/src/files/test_file_reading.py @@ -70,6 +70,23 @@ def test_files_open(): assert file.closed + with open('src/files/write_file.txt', 'w') as file: + file.write('apple\n') + file.write('banana\n') + + with open('src/files/write_file.txt', 'a') as file: + file.write('pineapple\n') + + + with open('src/files/write_file.txt', 'r') as file: + read_data = file.read() + + assert read_data == ( + 'apple\n' + 'banana\n' + 'pineapple\n' + ) + # If you’re not using the with keyword, then you should call f.close() to close the file and # immediately free up any system resources used by it. If you don’t explicitly close a file, # Python’s garbage collector will eventually destroy the object and close the open file for you, diff --git a/src/files/write_file.txt b/src/files/write_file.txt new file mode 100644 index 00000000..4cfb606e --- /dev/null +++ b/src/files/write_file.txt @@ -0,0 +1,3 @@ +apple +banana +pineapple