Pythonのreadline() / readlines() で行末の改行を削除する。

pythonでファイルを開き、readlines()で読み込んだらリストの各要素に '\r\n' がくっついていたのでそれを削除する方法のメモ。

なんでこれが大事かというと、MP4のチャプター名。のところで、フレーム番号と時間の変換を行い、さらにチャプター名を処理しようとしたときに、フレーム番号だけの行なのに isdecimal() で False が返ってきたから。

簡単なのは str.rstrip() で削除してしまうことなんだけれど、ちょっと試してみます。

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> s='1234\r\n'
>>> s
'1234\r\n'
>>> print(s)
1234

>>> s.rstrip()
'1234'
>>> print(s.rstrip())
1234
>>> s.isdecimal()
False
>>> s.rstrip().isdecimal()
True
>>>

という感じ。

rstrip()はオンラインマニュアルによると次のように書いてあります。
Description
Returns a copy of the string with trailing characters removed.

Syntax
str. rstrip([chars])

chars
Optional. String specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped.

'trailing characters' というのは末尾の文字のことで、'末尾の文字を削除した文字列のコピーを返す' という説明になっていますが、引数の 'chars' が省略されたときには 'whitespace' を削除することになっています。ここで、'whitespace'の定義は次のようになっていました。
string.whitespace
A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.
'whitespace' とは、「whitespaceと考えられるすべてのASCII文字を含む文字列のこと。空白、タブ、行送り、行頭復帰、用紙送りと垂直タブ文字のこと。」だそうです。

一般にテキストファイルでの改行文字は、UNIXでは '\n'、Macでは '\r'、Windowsでは '\r\n' ですが、rstrip()はこれらすべてに対応するようです。

0 件のコメント:

コメントを投稿

WesternDigitalこわれた。

たぶん寿命を過ぎてるのでクレームとまではいかないのだけれど。 WesternDigitalのWD60EFRXが壊れました。モノは2014年11月に購入。ところが3年で壊れ、RMAにより2017年11月に交換したものです。BlackBlazeでも故障率がそれなりに高かったので、そう...