Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonを使用してテキストファイルに1行を書き込む方法は?


書き込み関数を使用してファイルに行を書き込むことができます。

f = open('myfile', 'w')
f.write('hi there\n')  # python will convert \n to os.linesep
f.close()  # you can omit in most cases as the destructor will call it

または、Python 2.6以降で使用できるprint()関数を使用することもできます

from __future__ import print_function  # Only needed for Python 2
print("hi there", file=f)

Python 3の場合、print()関数がデフォルトであるため、インポートは必要ありません。


  1. Python-パンダのデータフレームをCSVファイルに書き込む方法

    pandasデータフレームをPythonでCSVファイルに書き込むには、 to_csv()を使用します 方法。まず、リストの辞書を作成しましょう- # dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_purchase': ['2020-10-10', '2020-10-12', '

  2. Pythonモジュールを単一のファイルにカプセル化する方法は?

    通常、Pythonモジュールを1つのファイルにカプセル化することはできません。そうすると、Pythonが使用するモジュール検索方法(ファイルとディレクトリ)が破壊されるためです。マシンにモジュールをインストールできない場合(十分な権限がないため)、virtualenvを使用するか、モジュールファイルを別のディレクトリに保存し、次のコードを使用して、Pythonが特定のモジュール内のモジュールを検索できるようにします。 >>> import os, sys >>> file_path = 'AdditionalModules/' >&g