Python でのファイル処理 は、幅広い操作を実行するために使用できる強力で多用途のツールです。ただし、コードが安全で信頼性が高く、適切に実行されるようにするには、Python プログラムを作成するときにファイル処理の長所と短所を慎重に考慮することが重要です。
この記事では、 Python ファイルの処理、利点、欠点、および Python ファイルでの open、write、append 関数の動作方法。
Python ファイルの処理
Python はファイル処理をサポートしており、ユーザーがファイルを処理できるようにします。つまり、ファイルの読み取りと書き込みだけでなく、他の多くのファイル処理オプションとともにファイルを操作することもできます。ファイル処理の概念は他のさまざまな言語にも広がっていますが、Python の他の概念と同様に、実装は複雑または時間がかかりますが、ここでのこの概念も簡単で短いものです。 パイソン はファイルをテキストまたはバイナリとして別々に扱いますが、これは重要です。コードの各行には一連の文字が含まれており、テキスト ファイルを形成します。ファイルの各行は、 EOL または 行末 のようなキャラクター コンマ {,} または 改行文字。 現在の行を終了し、新しい行が開始されたことをインタープリタに伝えます。ファイルの読み取りと書き込みから始めましょう。
Python でのファイル処理の利点
- 多用途性 : Python でのファイル処理を使用すると、ファイルの作成、読み取り、書き込み、追加、名前変更、削除などの幅広い操作を実行できます。
- 柔軟性 : Python でのファイル処理は、さまざまなファイル タイプ (例: テキスト ファイル、バイナリ ファイル、 CSVファイル 、など)、ファイルに対してさまざまな操作 (読み取り、書き込み、追加など) を実行します。
- ユーザー – フレンドリー : Python はファイル処理のためのユーザーフレンドリーなインターフェイスを提供し、ファイルの作成、読み取り、操作を簡単にします。
- クロスプラットフォーム : Python のファイル処理関数はさまざまなプラットフォーム (Windows、Mac、Linux など) で動作し、シームレスな統合と互換性を実現します。
Python でのファイル処理の欠点
- エラーを起こしやすい: Python でのファイル処理操作は、特にコードが注意深く書かれていない場合、またはファイル システムに問題がある場合 (ファイルのアクセス許可、ファイルのロックなど)、エラーが発生しやすい可能性があります。
- セキュリティリスク : Python でのファイル処理は、特にシステム上の機密ファイルへのアクセスや変更に使用される可能性のあるユーザー入力をプログラムが受け入れる場合、セキュリティ リスクを引き起こす可能性があります。
- 複雑 : Python でのファイル処理は、特により高度なファイル形式や操作を扱う場合、複雑になることがあります。ファイルが適切かつ安全に処理されるように、コードには細心の注意を払う必要があります。
- パフォーマンス : Python でのファイル処理操作は、特に大きなファイルを処理する場合や複雑な操作を実行する場合、他のプログラミング言語よりも遅くなる可能性があります。
この記事では、次のことを考慮します オタク.txt ファイルを例として挙げます。
Hello world techcodeview.com 123 456>
Python ファイルを開く
ファイルに対して読み取りや書き込みなどの操作を実行する前に、まずそのファイルを開く必要があります。このためには、Python の組み込み関数を使用する必要があります。 開ける() ただし、開くときに、ファイルを開く目的を表すモードを指定する必要があります。
f = open(filename, mode)>
次のモードがサポートされている場合:
- r: 読み取り操作のために既存のファイルを開きます。
- で: 書き込み操作のために既存のファイルを開きます。ファイルに既にデータが含まれている場合は上書きされますが、ファイルが存在しない場合はファイルも作成されます。
- 答え: 追加操作のために既存のファイルを開きます。既存のデータは上書きされません。
- r+: ファイルへのデータの読み取りと書き込み。ファイル内の以前のデータは上書きされます。
- w+: データの書き込みと読み取り。既存のデータは上書きされます。
- α+: ファイルへのデータの追加およびファイルからのデータの読み取り。既存のデータは上書きされません。
読み取りモードでの作業
方法は複数あります Pythonでファイルから読み取る方法 。読み取りモードでファイルの内容を読み取る方法を見てみましょう。
例 1: open コマンドは Python ファイルを読み取りモードで開き、for ループはファイル内の各行を出力します。
Python3
# a file named 'geek', will be opened with the reading mode.> file> => open> (> 'geek.txt'> ,> 'r'> )> # This will print every line one by one in the file> for> each> in> file> :> > print> (each)> |
>
>
出力:
Hello world techcodeview.com 123 456>
例 2: この例では、Python ファイル内のすべての文字を含む文字列を抽出します。 file.read() 。
Python3
# Python code to illustrate read() mode> file> => open> (> 'geeks.txt'> ,> 'r'> )> print> (> file> .read())> |
>
>
出力:
Hello world techcodeview.com 123 456>
例 3: この例では、次のコマンドを使用してファイルを読み取る方法を見ていきます。 と 声明 Pythonで。
Python3
# Python code to illustrate with()> with> open> (> 'geeks.txt'> ) as> file> :> > data> => file> .read()> print> (data)> |
>
>
出力:
Hello world techcodeview.com 123 456>
例 4: ファイルを読み取るもう 1 つの方法は、次のコードのように特定の数の文字を呼び出すことです。インタプリタは保存されたデータの最初の 5 文字を読み取り、それを文字列として返します。
Python3
月に何週間
# Python code to illustrate read() mode character wise> file> => open> (> 'geeks.txt'> ,> 'r'> )> print> (> file> .read(> 5> ))> |
>
>
出力:
Hello>
例 5: Python でファイルを読み込むときに行を分割することもできます。 split() 関数は、スペースが見つかったときに変数を分割します。必要に応じて、任意の文字を使用して分割することもできます。
Python3
# Python code to illustrate split() function> with> open> (> 'geeks.txt'> ,> 'r'> ) as> file> :> > data> => file> .readlines()> > for> line> in> data:> > word> => line.split()> > print> (word)> |
>
>
出力:
['Hello', 'world'] ['techcodeview.com'] ['123', '456']>
write() 関数を使用したファイルの作成
Python でファイルを読み取るのと同じように、さまざまな方法があります。 Python でファイルに書き込む 。 Python の write() 関数を使用してファイルの内容を書き込む方法を見てみましょう。
書き込みモードでの作業
ファイルの作成方法と書き込みモードの仕組みを見てみましょう。
例 1: この例では、書き込みモードと write() 関数を使用してファイルに書き込む方法を見ていきます。 close() コマンドは、使用中のすべてのリソースを終了し、この特定のプログラムのシステムを解放します。
Python3
# Python code to create a file> file> => open> (> 'geek.txt'> ,> 'w'> )> file> .write(> 'This is the write command'> )> file> .write(> 'It allows us to write in a particular file'> )> file> .close()> |
>
>
出力:
This is the write commandIt allows us to write in a particular file>
例 2: 書かれたステートメントを with() 関数と一緒に使用することもできます。
Python3
# Python code to illustrate with() alongwith write()> with> open> (> 'file.txt'> ,> 'w'> ) as f:> > f.write(> 'Hello World!!!'> )> |
>
>
出力:
Hello World!!!>
追加モードの動作
追加モードがどのように機能するかを見てみましょう。
例: この例では、前の例で作成した Python ファイルを使用します。
Python3
# Python code to illustrate append() mode> file> => open> (> 'geek.txt'> ,> 'a'> )> file> .write(> 'This will add this line'> )> file> .close()> |
>
>
出力:
This is the write commandIt allows us to write in a particular fileThis will add this line>
Python ファイル処理には、さまざまなタスクを処理するために使用される他のさまざまなコマンドもあります。
rstrip(): This function strips each line of a file off spaces from the right-hand side. lstrip(): This function strips each line of a file off spaces from the left-hand side.>
コードを操作する際に、より簡潔な構文と例外処理を提供するように設計されています。これは、該当する場合にはステートメントでこれらを使用することをお勧めする理由を説明しています。この方法を使用すると、開いたファイルは完了後に自動的に閉じられるため、自動クリーンアップが行われるため、これは便利です。
ファイル処理のすべての関数を実装する
この例では、上で見たすべての概念を取り上げます。これら以外に、Python から Remove() 関数を使用してファイルを削除する方法も見ていきます。 OSモジュール 。
Python3
import> os> def> create_file(filename):> > try> :> > with> open> (filename,> 'w'> ) as f:> > f.write(> 'Hello, world!
'> )> > print> (> 'File '> +> filename> +> ' created successfully.'> )> > except> IOError:> > print> (> 'Error: could not create file '> +> filename)> def> read_file(filename):> > try> :> > with> open> (filename,> 'r'> ) as f:> > contents> => f.read()> > print> (contents)> > except> IOError:> > print> (> 'Error: could not read file '> +> filename)> def> append_file(filename, text):> > try> :> > with> open> (filename,> 'a'> ) as f:> > f.write(text)> > print> (> 'Text appended to file '> +> filename> +> ' successfully.'> )> > except> IOError:> > print> (> 'Error: could not append to file '> +> filename)> def> rename_file(filename, new_filename):> > try> :> > os.rename(filename, new_filename)> > print> (> 'File '> +> filename> +> ' renamed to '> +> new_filename> +> ' successfully.'> )> > except> IOError:> > print> (> 'Error: could not rename file '> +> filename)> def> delete_file(filename):> > try> :> > os.remove(filename)> > print> (> 'File '> +> filename> +> ' deleted successfully.'> )> > except> IOError:> > print> (> 'Error: could not delete file '> +> filename)> if> __name__> => => '__main__'> :> > filename> => 'example.txt'> > new_filename> => 'new_example.txt'> > create_file(filename)> > read_file(filename)> > append_file(filename,> 'This is some additional text.
'> )> > read_file(filename)> > rename_file(filename, new_filename)> > read_file(new_filename)> > delete_file(new_filename)> |
>
>
出力:
File example.txt created successfully. Hello, world! Text appended to file example.txt successfully. Hello, world! This is some additional text. File example.txt renamed to new_example.txt successfully. Hello, world! This is some additional text. File new_example.txt deleted successfully.>