0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonで複数行サイズ指定読み込み

Posted at

pythonで複数行読み込み

pythonでファイルを複数行に分けて読み込みたくて試してみたので備忘録として残しておきます。

<結果>
サイズ指定は文字数で途中までの文字数を指定するとその行の
最後まで読み込む。
改行はカウントされない。ゼロは全行読み込む
 

<環境>
バージョン:Python 3.8.5
windows 10

<詳細>
ファイルの内容

abcdefghijklmnopqrstuvwxyz
12345678901234567890
ABCDEFGHIJKLMNOPQRSTUVWXYZ

1行目の途中を指定.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 = <class 'list'> ['abcdefghijklmnopqrstuvwxyz\n']

2行目の途中を指定.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 = <class 'list'> ['abcdefghijklmnopqrstuvwxyz\n', '12345678901234567890\n']

ファイルの内容

あいうえおかきくけこさしすせそ
12345678901234567890
ABCDEFGHIJKLMNOPQRSTUVWXYZ

1行目の改行前を指定.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 = <class 'list'> ['あいうえおかきくけこさしすせそ\n']

1行目の改行を指定のつもりだけど2行目の先頭.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 = <class 'list'> ['あいうえおかきくけこさしすせそ\n', '12345678901234567890\n']

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 = <class 'list'> ['あいうえおかきくけこさしすせそ\n', '12345678901234567890\n', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?