Python Write/Create Files

Python File Write – Python Файл бичих #

Write to an Existing File – Байгаа файлд бичих #

To write to an existing file, you must add a parameter to the open() function:

Файлд бичихийн тулд open() функцэд параметр нэмэх хэрэгтэй:

"a" – Append – will append to the end of the file

"a" – Нэмэх – Файлын төгсгөлд шинэ агуулга нэмнэ.

"w" – Write – will overwrite any existing content

"w" – Бичих – Файлд байгаа агуулгыг дарж бичих болно.

Example – Жишээ #

Open the file “demofile2.txt” and append content to the file:

“demofile2.txt” файлыг нээж, агуулга нэмэх:

f = open("demofile2.txt""a")
f.write("Now the file has more content!")
f.close()
# Файлыг нээж, нэмэгдсэн агуулгыг унших:
f = open("demofile2.txt""r")
print(f.read())

Example – Жишээ #

Open the file “demofile3.txt” and overwrite the content:

“demofile3.txt” файлыг нээж, агуулгыг дахин бичих:

f = open("demofile3.txt""w")
f.write("Woops! I have deleted the content!")
f.close()
# Файлыг нээж, дахин бичигдсэн агуулгыг унших:
f = open("demofile3.txt""r")
print(f.read())

Note: the "w" method will overwrite the entire file.

Анхаар: "w" арга нь файлын бүх агуулгыг дахин бичнэ.

Create a New File – Шинэ файл үүсгэх #

To create a new file in Python, use the open() method, with one of the following parameters:

Python-д шинэ файл үүсгэхийн тулд open() аргыг дараах параметрүүдийн аль нэгтэй ашиглана:

"x" – Create – will create a file, returns an error if the file exist

"x" – Шинэ файл үүсгэх – Файл аль хэдийн байвал алдаа өгнө.

"a" – Append – will create a file if the specified file does not exist

"a" – Нэмэх – Хэрэв заасан файл байхгүй бол шинэ файл үүсгэнэ.

"w" – Write – will create a file if the specified file does not exist

"w" – Бичих – Хэрэв заасан файл байхгүй бол шинэ файл үүсгэнэ.

Example – Жишээ #

Create a file called “myfile.txt”:

“myfile.txt” нэртэй файл үүсгэх:

f = open("myfile.txt""x")

Result: a new empty file is created!

Үр дүн: шинэ хоосон файл үүснэ!

Example – Жишээ #

Create a new file if it does not exist:

Хэрэв файл байхгүй бол шинэ файл үүсгэх:

f = open("myfile.txt""w")

Powered by BetterDocs

Leave a Reply