Python の write() 関数と writelines() 関数の違い
Python には、ファイルを読み書きするための関数が多数あります。読み取り関数と書き込み関数は両方とも、開いているファイル (ファイル オブジェクトを介して開かれ、リンクされているファイル) に対して機能します。このセクションでは、ファイルを通じてデータを操作するための書き込み関数について説明します。
write() 関数
write() 関数は、余分な文字を追加せずにファイルの内容を書き込みます。
構文 :
# Writes string content referenced by file object. file_name.write(content)
構文に従って、write() 関数に渡される文字列は、開いているファイルに書き込まれます。文字列には、数字、特殊文字、または記号が含まれる場合があります。ファイルにデータを書き込むとき、write 関数は文字列の末尾に改行文字 ( ) を追加しないことを知っておく必要があります。 write() 関数は None を返します。
例:
Python3
file> => open> (> 'Employees.txt'> ,> 'w'> )> > for> i> in> range> (> 3> ):> > name> => input> (> 'Enter the name of the employee: '> )> > file> .write(name)> > file> .write(> '
'> )> > file> .close()> > print> (> 'Data is written into the file.'> )> |
出力:
Data is written into the file.
サンプル実行:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil
writelines() 関数
この関数は、リストの内容をファイルに書き込みます。
構文 :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)
構文に従って、writelines() 関数に渡される文字列のリストは、開いているファイルに書き込まれます。 write() 関数と同様に、writelines() 関数は文字列の末尾に改行文字 ( ) を追加しません。
例:
Python3
file1> => open> (> 'Employees.txt'> ,> 'w'> )> lst> => []> for> i> in> range> (> 3> ):> > name> => input> (> 'Enter the name of the employee: '> )> > lst.append(name> +> '
'> )> > file1.writelines(lst)> file1.close()> print> (> 'Data is written into the file.'> )> |
出力:
Data is written into the file.
サンプル実行:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul
唯一の違いは、 書く() そして 書き込みライン() write() メソッドは既に開かれているファイルに文字列を書き込むために使用され、writelines() メソッドは開かれたファイルに文字列のリストを書き込むために使用されます。