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

Python read / write file

編輯:Python

Author:AXYZdong Automation Engineering Male

File and file path

Two key attributes of files : file name and route ( Indicates the location of the file on the computer )

Windows On , The path is written with a backslash \ As a separator between folders

OS X and Linux On , Use forward slashes / As the separator of the path .

Current working directory

Every program running on the computer , There is one. “ Current working directory ”, or cwd. There is no file name or path starting from the root folder , Are assumed to be in the current working directory .os.getcwd() Function to get the string of the current working path , You can use os.chdir() Change it .

>>>os.getcwd() # Get the current working path ,cwd(current work directory): Current working path
'D:\\Python Study'

Absolute path and relative path

  • Absolute path : Always start from the root folder .
  • Relative paths : Relative to the current working directory of the program .
Absolute path and relative path

use os.makedirs() Create a new folder

>>>import os
>>>os.makedirs('.\\read1')
>>>os.makedirs('D:\\Python study\\read2')

os.makedirs('.\\read1'): Relative paths , Means to create... Under the current working directory read1 Folder .

os.makedirs('D:\\Python study\\read2'): Absolute path , stay D Discoid Python Study Create under folder read2 Folder .

To ensure that the full pathname exists , If the intermediate folder does not exist ,os.makedirs() All necessary intermediate folders will be created .

os.path modular

os.path The module contains many useful functions related to file names and file paths .os.path yes os Module in module ,import os You can import it .os.path Complete documentation of the module :http://docs.python.org/3/library/os.path.html .

Deal with absolute (absolute) Path and relative (relative) route

  • os.path.abspath(path) Returns the string of the absolute path of the parameter , Facilitate the conversion of relative path to absolute path .
  • os.path.isabs(path) Determine whether the parameter is an absolute path , If so, return True, Otherwise return to False.
  • os.path.relpath(path,start) Will return from start To path The string of the relative path of , If not provided start , Default the current working directory as the starting path .
  • os.path.dirname(path) Will return a string , contain path Everything before the last slash in the parameter .( The directory name is returned )
  • os.path.basename(path) Will return a string , contain path Everything after the last slash in the parameter .( The basic name is returned )
  • os.path.split(path) Return the directory name and basic name of a path at the same time , Get the tuple containing these two strings .
>>>import os
>>>path = 'C:\\Windows\\System32\\calc.exe'
>>>os.path.abspath(path)
'C:\\Windows\\System32\\calc.exe'
>>>os.path.isabs(path)
True
>>>os.path.relpath(path,'C:\\Windows')
'System32\\calc.exe'
>>>os.path.dirname(path)
'C:\\Windows\\System32'
>>>os.path.basename(path)
'calc.exe'
>>>os.path.split(path)
('C:\\Windows\\System32', 'calc.exe')

View file size and folder contents

  • os.path.getsize(path) return path Folder size under path .
  • os.listdir(path) return path List of file name strings under path .
>>>path = os.getcwd()
>>>os.path.getsize(path)
4096
>>>os.listdir(path)
['.idea', 'Data Visualization', 'demo', 'demo.py', 'demo_1.py', 'paper.png', 'PDF synthesis ', 'text.py', 'turtle', 'watermark', 'wordcloud', '__pycache__', ' lantern .py', ' Crawling pictures .py', ' veil .jpg']

Check the validity of the path

  • os.path.exists(path) Judge path Whether the file or folder specified by the parameter exists , Return if present True, Otherwise return to False.
  • os.path.isfile(path) Judge path Whether the parameter is a file , If so, return True, Otherwise return to False.
  • os.path.isdir(path) Judge path Whether the parameter is a folder , If so, return True, Otherwise return to False.
>>>path = os.getcwd()
>>>os.path.exists(path)
True
>>>os.path.exists('D:\\read')
False
>>>os.path.exists('D:\\Python study')
True
>>>os.path.isfile(path)
False
>>>os.path.isdir(path)
True
>>>os.path.isfile('D:\\Python Study\\demo.py')
True

utilize os.path.exists() function Can be determined DVD Or whether the flash drive is currently connected to the computer . ( I don't have... On my current computer F Discoid )

>>>os.path.exists('F:\\')
False

File reading and writing process

Plain text file : Contains only basic text characters , Does not contain fonts 、 Size and color information . Such as : with .txt Extension text file , with .py Extended name Python Script files .

Three steps for reading and writing files :

  1. call open() function , Return to one File object .
  2. call File Object's read() or write() Method .
  3. call File Object's close() Method , Close the file .
open Several modes of opening files
Character Meaning --------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)

Create in current directory one.txt text file , And successively write Hello world! and my name is axyzdong.

>>>onefile = open('one.txt','w') # Open text in write mode
>>>onefile.write('Hello world!\n')
13
>>>onefile.close()
>>>onefile = open('one.txt','a') # Open text in add mode
>>>onefile.write('my name is axyzdong')
19
>>>onefile.close()
>>>onefile = open('one.txt')
>>>content = onefile.read()
>>>onefile.close()
>>>print(content)
Hello world!
my name is axyzdong

use shelve Module save variables

Use shelve The module will Python The variables in the program are saved to binary shelf In file .

step :

  1. import shelve
  2. Call function shelve.open() And pass in a file name , The value is then returned (shelf value ) Save in a variable .( You can change the value of this variable shelf Value to modify , It's like a dictionary )
  3. Call... In the returned object close() Method

shelve.open() Open files can be read and written by default , Like a dictionary shelf Value has keys() and values() Method , return shelf Keys and key values in .

use pprint.pformat() The function holds the variable , And write .py file

Use occasion : Suppose there is a dictionary , Save in a variable , You want to save this variable and its contents , It can be used at this time pprint.pformat() Function to hold this variable , And write it in .py file . This file will become a module , You can call it when you need it .

>>>import pprint
>>>characters = {'one':'a','two':'b'}
>>>pprint.pformat(characters)
"{'one': 'a', 'two': 'b'}"
>>>file = open('characters.py','w')
>>>file.write('characters = '+ pprint.pformat(characters) + '\n')
38
>>>file.close()
>>>import characters
>>>characters.characters
{'one': 'a', 'two': 'b'}
>>>characters.characters['one']
'a'

such , There will be a in the current working directory characters.py file , It only contains One line of code characters = {'one': 'a', 'two': 'b'}

Create a .py The advantage of the file is ,.py A file is a text file , Anyone can use a simple text editor to read and modify the contents of the file .

reference

1:Python Programming fast : Automate tedious work / ( beautiful ) Svegart (A1 Sweigart) Writing ; Translated by Wang Haipeng . Beijing : People's post and Telecommunications Press ,2016.7

This sharing is here


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