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

Python persistent storage file operation

編輯:Python

One 、 The basic operation of the file

# 1. Open file
"""
mode:
r: Can only read documents
w: Write only ( Clear the contents of the file first )
a+: Reading and writing ( File append write content )
r+: Reading and writing ( Write contents at the beginning of the file )
"""
f = open('doc/hello',mode='r+')
# 2. File read and write operations
f.write('javaaaaa\n')
# 3. Close file
f.close()


Make an example of the above figure explain :
frequently-used mode Yes r、w、a
r: r It's a read operation , By default, there is .( But when mode When it becomes another type Not necessarily )
w: involve w Of mode, Whether it's w still w+, The contents of the file will be emptied first
a: a It's the mildest mode 了 , He will not empty the contents of the file . But no read permission .
+:a+ and r+ Both have read and write operations .

Two 、 In file operation with sentence

As can be seen from the above , I'm doing... On the file open And after the read / write operation , Finally, use close Turn it off , Release resources .
This involves closing the file :
Method 1 : call close() Method Close file . The file must be closed after use , Because file objects take up operating system resources ,
And the operating system can open a limited number of files at the same time :

Method 2 : Python Introduced with sentence Come on Automatically call for us close() Method :

Here are two pieces of code to understand :
Example 1 :

with open('doc/test',mode='w+') as f:
f.write('javavaaaa\n')
print(f.read())

The result here is empty , Namely print Unable to read results , Why? ?
Because it involves pointers , When put javavaaaa After adding to the file , The pointer points to the last character , Of course he didn't have anything after that , So the output is null .

Last Make a summary of the above :

with open('doc/test',mode='w+') as f:
f.write('java\n')
f.seek(0,0)
print(' The position of the current pointer :',f.tell())
f.seek(0,2)
print(' The position of the current pointer :',f.tell())
print(f.read())

seek(offset, from) Yes 2 Parameters : offset: Offset from: Direction
0: Indicates the beginning of the file ;
1: Indicates the current location ;
2: Indicates the end of the file

3、 ... and 、os modular

os, Semantic is operating system , Dealing with operating system related functions , Cross platform . For example, display all files in the current directory / Delete a file / Get file size ……

import os
import platform
# 1. Get the operating system type
print(os.name)
# 2. Get host information ,windows System use platform modular , If it is Linux System use os modular
"""
try: There may be an error code
excpt: If there is an anomaly , What to do
finally: Is there anything abnormal , Will be implemented
"""
try:
uname = os.uname()
except Exception:
uname = platform.uname()
finally:
print(uname)
# 3. Get the environment variables of the system
envs = os.environ
# os.environ.get('PASSWORD')
print(envs)
#4. Determine whether it is an absolute path and generate an absolute path
print(os.path.isabs('D:\Program Files\pycharm\ Automation operation and maintenance project \day04'))
print(os.path.isabs('day05'))
print(os.path.abspath('day06'))
# 5. Directory name and file name stitching
# os.path.dirname Get the directory name of a file
# __file__ Current file
# join Splicing , Put the directory name and the file name together .
print(os.path.dirname(__file__)) ## Get the absolute path of the current file
print(os.path.basename(__file__)) ## Get the current file name
BASE_DIR = os.path.dirname(__file__)
setting_file = os.path.join(BASE_DIR,'hellooo.conf')
print(setting_file)

Four 、json modular

JSON(JavaScript Object Notation) It's a lightweight Data exchange format . It's based on ECMAScript A subset of .

python Type data and JSON Data format conversion rules

import json
# 1. take python The object is encoded as json character string
users = {'name':'westos', "age":18, 'city':' Xi'an '}
json_str = json.dumps(users)
with open('doc/hello.json', 'w') as f:
# ensure_ascii=False: Chinese can be stored successfully
# indent=4: Indent to 4 A space
json.dump(users, f, ensure_ascii=False, indent=4)
print(" Storage success ")
print(json_str, type(json_str))
# 2. take json The string is decoded into python object
with open('doc/hello.json') as f:
python_obj = json.load(f)
print(python_obj, type(python_obj))

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