GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — learn-python/src/files/test_file_methdos.py at master · aronjames/learn-python Expand file tree/ Copy pathtest_file_methdos.pyMore file actions 47 lines (36 loc) · 2.3 KB / Copy pathtest_file_methdos.pyFile metadata and controls47 lines (36 loc) · 2.3 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 """Methods of File Objects @see: https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects """ def test_file_methods(): """Methods of File Objects""" multi_line_file = open('src/files/multi_line_file.txt', 'r') binary_file = open('src/files/binary_file', 'r') # To read a file’s contents, call f.read(size), which reads some quantity of data and returns # it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric # argument. When size is omitted or negative, the entire contents of the file will be read and # returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, # at most size bytes are read and returned. If the end of the file has been reached, f.read() # will return an empty string (''). read_data = multi_line_file.read() # pylint: disable=duplicate-code assert read_data == 'first line\nsecond line\nthird line' # To change the file object’s position, use f.seek(offset, from_what). The position is computed # from adding offset to a reference point; the reference point is selected by the from_what # 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(6) == 6 # Go to the 6th byte in the file assert binary_file.read(1) == '6' # 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 # newline. This makes the return value unambiguous; if f.readline() returns an empty string, # the end of the file has been reached, while a blank line is represented by '\n', a string # containing only a single newline. multi_line_file.seek(0) assert multi_line_file.readline() == 'first line\n' assert multi_line_file.readline() == 'second line\n' assert multi_line_file.readline() == 'third line' assert multi_line_file.readline() == '' multi_line_file.close() binary_file.close() |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |