Multi-line size specification reading with python

Read multiple lines with python

I tried to read the file in multiple lines with python, so I will leave it as a memorandum.

The size is specified by the number of characters, and if you specify the number of characters halfway, the line Read to the end. Line breaks are not counted. Zero reads all lines   Version: Python 3.8.5 windows 10
File contents > abcdefghijklmnopqrstuvwxyz 12345678901234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZ

Specify the middle of the first line.py


def readlines( fname ):
    with open( fname, 'r') as f:
        readData = f.readlines( 20 )
    return readData

if __name__ == '__main__':
    fname = './Dmy.txt'
    readData = readlines( fname )
    print( f' readData = {type(readData)} {readData}')
> readData = \ ['abcdefghijklmnopqrstuvwxyz\n']

Specify the middle of the second line.py


def readlines( fname ):
    with open( fname, 'r') as f:
        readData = f.readlines( 30 )
    return readData

if __name__ == '__main__':
    fname = './Dmy.txt'
    readData = readlines( fname )
    print( f' readData = {type(readData)} {readData}')
> readData = \ ['abcdefghijklmnopqrstuvwxyz\n', '12345678901234567890\n']

File contents </ u>

Aiue Okakikuke Kosashi Sesso 12345678901234567890 ABCDEFGHIJKLMNOPQRSTUVWXYZ

Specify before line break on the first line.py


def readlines( fname ):
    with open( fname, 'r') as f:
        readData = f.readlines( 15 )
    return readData

if __name__ == '__main__':
    fname = './Dmy.txt'
    readData = readlines( fname )
    print( f' readData = {type(readData)} {readData}')
> readData = \ ['aiueokakikukekosashisuseso \ n']

I intend to specify a line break on the first line, but the beginning of the second line.py


def readlines( fname ):
    with open( fname, 'r') as f:
        readData = f.readlines( 16 )
    return readData

if __name__ == '__main__':
    fname = './Dmy.txt'
    readData = readlines( fname )
    print( f' readData = {type(readData)} {readData}')
> readData = \ ['aiueokakikukekosashisuseso \ n', '12345678901234567890 \ n']

Specify 0.py


def readlines( fname ):
    with open( fname, 'r') as f:
        readData = f.readlines( 0 )
    return readData

if __name__ == '__main__':
    fname = './Dmy.txt'
    readData = readlines( fname )
    print( f' readData = {type(readData)} {readData}')
> readData = \ ['Aiue Okakikuke Kosashi Suseso \ n', '12345678901234567890 \ n','ABCDEFGHIJKLMNOPQRSTUVWXYZ']

Recommended Posts