Методы создания текстового файла в Python

Чтобы создать текстовый файл в Python, вы можете использовать несколько методов. Вот некоторые распространенные подходы:

Метод 1: использование функции open()с режимом 'w'

file_path = 'example.txt'  # Specify the file path
text = 'This is the content of the text file.'  # Content to write in the file
with open(file_path, 'w') as file:
    file.write(text)

Метод 2: использование функции open()с режимом 'x'

file_path = 'example.txt'  # Specify the file path
text = 'This is the content of the text file.'  # Content to write in the file
try:
    with open(file_path, 'x') as file:
        file.write(text)
except FileExistsError:
    print("File already exists.")

Метод 3: использование метода write()файлового объекта

file_path = 'example.txt'  # Specify the file path
text = 'This is the content of the text file.'  # Content to write in the file
file = open(file_path, 'w')
file.write(text)
file.close()

Метод 4. Использование модуля Pathиз библиотеки pathlib

from pathlib import Path
file_path = Path('example.txt')  # Specify the file path
text = 'This is the content of the text file.'  # Content to write in the file
file_path.write_text(text)

Метод 5. Использование модуля io

import io
file_path = 'example.txt'  # Specify the file path
text = 'This is the content of the text file.'  # Content to write in the file
with io.open(file_path, 'w', encoding='utf-8') as file:
    file.write(text)