How to read a number of characters from a text file using Python?

PythonServer Side ProgrammingProgramming

To read a file’s contents, you can call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned. 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 ("").

So if you want to read 10 ASCII characters, you can simply pass 10 as the argument.

For example

>>> f = open('my_file', 'r')
>>> print(f.read(10))
Hello worl
>>> f.close()
raja
Published on 22-Dec-2017 11:36:35
Advertisements