程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python create / write file

編輯:Python

Also use open function .

1) In principle , Create should use x Pattern .

open(r".\newfile.txt","x")

Files will be created in the same directory newfile.txt.

however , If newfile.txt Already exist , May be an error :

Traceback (most recent call last):
File "C:\Users\***\Desktop\MEME\1.py", line 1, in <module>
open(r".\newfile.txt","x")
FileExistsError: [Errno 17] File exists: '.\\newfile.txt'

therefore , A good solution :

import os
if not os.path.exists(r".\newfile.txt"):
open(r".\newfile.txt","x")

Use os The module determines whether there is , Create if it does not exist .

2) Actually w The model is also good

w(write) Pattern , In theory, it is a write mode , But you can also create files .

Its greatest advantage is : You can create an existing file without reporting an error .      

however : Be careful !!!! The data of the existing file will be cleared

-_-||

So please be careful with .

3)w Mode writing

Write method :

a=open(r".\ty.txt","w")
a.write("texture")

That's all .

however : It will cover the original content .( There are some shortcomings in the beauty )

4) a Mode add

a(append) Mode will not be overwritten , Instead, add... At the end . however , If a The schema encountered a situation where the file does not exist , Will report a mistake ( No files found ).

a=open(r".\ty.txt","a")
a.write("texture")

This line of code will add... At the end of the file 【texture】 Text .

---------------------------------------------- End -----------------------------------------------------------------------------

author: Unconquerable&Llxy

Unconquerable&Llxy The blog of _CSDN Blog -Python From negative infinity to ~,Vpython-3D,our project1 Domain Blogger Unconquerable&Llxy Good at Python From negative infinity to ~,Vpython-3D,our project1, And so on ,Unconquerable&Llxy Focus on python field .https://blog.csdn.net/html_finder?type=blog Welcome to visit ^_^


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved