Python: file reading and writing

ファイルの読み書き
<1> データの書き込み(write)
write() を使用してファイルへのデータ書き込みを完了します
デモ:file_write_test.py という新しいファイルを作成し、以下のコードを記述します:

f = open('test.txt', 'w')
f.write('hello world, i am here。 ' * 5)
f.close()
実行後、file_write_test.py ファイルが配置されているパスに test.txt ファイルが作成され、内容が書き込まれます。実行結果は以下の通りです:
image.png
注意:
ファイルが存在しない場合は作成されます。存在する場合は、まず内容がクリアされてからデータが書き込まれます

<2> データの読み取り(read)
read(num) を使用してファイルからデータを読み取ります。num はファイルから読み取るデータの長さ(バイト単位)を示します。num を渡さない場合は、ファイル内のすべてのデータを読み取ることを意味します

デモ:file_read_test.py という新しいファイルを作成し、以下のコードを記述します:

f = open('test.txt', 'r')
content = f.read(5) # read up to 5 data
print(content)

print("-"*30) # dividing line for testing

content = f.read() # Continue to read all the remaining data from the last read position
print(content)

f.close() # close the file
実行結果:

hello
------------------------------
world, i am here。
注意:
「r」でファイルを開く場合、open('test.txt') を省略できます

<3> データの読み取り(readlines)
readline はファイル全体の内容を一度に行単位で読み取り、リストを返します。各行がリストの要素となります。

f = open('test.txt', 'r')
content = f.readlines()
print(type(content))

for temp in content:
print(temp)

f.close()
readline() は 1 行のデータを読み取ります

ポインターの位置決め
tell() メソッドは現在のポインター位置を表示するために使用します

f = open('test.txt')
print(f.read(10)) # read specifies the number of bytes read
print(f.tell()) # tell() method displays the text where the current file pointer is located
f.close()
seek(offset,whence) メソッドはポインターの位置をリセットするために使用します。

offset:オフセットを示します
whence:0、1、2 のいずれかの数値を渡すことができます。
0 はファイルの先頭から始まることを示します
1 は現在位置から始まることを示します
2 はファイルの末尾から始まることを示します
f = open('test.txt','rb') # Need to specify the opening mode as rb, read-only binary mode

print(f.read(3))
print(f.tell())

f.seek(2,0) # start from the beginning of the file, skip two bytes
print(f.read())

f.seek(1,1) # Start from the current position, skip a byte
print(f.read())

f.seek(-4,2) # Start from the end of the file, skip four bytes forward
print(f.read())

f.close()

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone お問い合わせ
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.