[Arsenal] Python OS: I read and write files thanks

Here Insert Picture Description


We write code procedure, you may be variable as a container to store data. But after the program data in order to remain, then the file must be saved in the data you want.

By using OS module, we can achieve on your hard disk to create, read and save the file.

First, the file and the file path

1. Basic Operation

First, recognize that the OS has four functions a method of operating a file and file path.

【01】os.path.join()

To pass a string on a single file path and file name for the folder it will return a file path character string, comprising the correct path separators.

Code demonstrates:

import os
mo = os.path.join('user','bin','spam')
print(mo)

myFile = ['accounts.txt','details.csv','invite.docx']
for filename in myFile:
    print(os.path.join('C:\\User\\asweigart',filename))

Output:
Here Insert Picture Description
[02] os.getcwd ()

Returns a string representation of the current working directory.

The current working directory working directory-oriented Python program is located.

Code demonstrates:

import os
print(os.getcwd())

Output:
Here Insert Picture Description

【03】os.chdir(path)

Change the current working directory for the file path parameters.

Precautions:

  1. If you want to change the current working directory does not exist, it will error
  2. Just change the current working directory, not the file will be transferred to the new working directory

Code demonstrates:

import os
print(os.getcwd())

os.chdir('E:\【05】编程设计\Python\Python自动化办公')
print(os.getcwd())

Output:
Here Insert Picture Description
[04] os.makedirs (path)

Create a new folder, and creates all necessary intermediate folder to make sure that the full path to exist.

Code demonstrates:

import os
os.makedirs(r'E:\【05】编程设计\111\222\333')

Output:
Here Insert Picture Description

——

2. Absolute and relative paths

[01] two important concepts

Two very important concepts must be mastered.

There are two ways we can specify a file path, absolute and relative paths.

Absolute path: always complete path from the root folder

Relative path: it is relative to the current working directory where the program

At the same time, we write the code in the program, usually a single dot stands for "current directory" (.); With two periods (...) on behalf of the parent folder, which is the parent folder.

[02] correlation function

Overview about the handling absolute and relative path method:

  • os.path.abspath (path) Returns the string parameters absolute path
  • os.path.isabs (path) if the parameter is an absolute path to return True, otherwise False
  • os.path.relpath (path, start) returns the relative path to the path start characters from the path. If no start on the path to the current working directory as the start
  • os.path.dirname (path) Returns the name of a directory path
  • os.path.basename (path) Returns the name of a path substantially
  • os.path.split (path) Returns a string tuple contains a directory name and base name
  • Variable .split (os.path.sep) returns the list of strings divided by slash cut path

There are two concepts need to understand that the path of the directory name and the base name
Here Insert Picture Description
code demonstrates:

import os

print(os.path.abspath('.'))
print(os.path.abspath('.\\001 os.path.join()'))
print(os.path.isabs('.'))
print(os.path.isabs(os.path.abspath('.')))
print(os.path.relpath(r'E:\【05】编程设计\Python\我的项目',r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件'))

path = r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件\004 处理绝对和相对路径'
print(os.path.dirname(path))
print(os.path.basename(path))
print(os.path.split(path))
print(path.split(os.path.sep))

Output:
Here Insert Picture Description

——

3. View folder size and content

This block functions relates to two methods

  • os.path.getsize (path) path returns the number of bytes in the file parameter
  • os.listdir (path) Returns the file path name string parameter list

Code demonstrates:

import os

print(os.path.getsize('.\\005 查看文件大小和文件夹内容.py'))
print(os.listdir('.'))

Output:
Here Insert Picture Description
If you want to know the total number of bytes in a directory of all the files, we can do so.

import os

totalSize = 0
for filename in os.listdir('.'):
    totalSize += os.path.getsize(os.path.join('.',filename))
print(totalSize)

Here Insert Picture Description
——

4. Check the validity of the path

This block functions relates to three methods

  • os.path.exists (path) if the path parameter refers to the file or folder exists, returns True
  • The os.path.isfile (path) if the path parameter and the presence of a document returns True
  • os.path.isdir (path) if the path parameter exists and is a folder, returns True

Code demonstrates:

import os

print(os.path.exists(r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件'))
print(os.path.isfile(r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件'))
print(os.path.isdir(r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件'))

Output:
Here Insert Picture Description
Small Tip: We can os.path.exists () function determining whether the current DVD or U disk connected to the computer.
Here Insert Picture Description

Second, the process of reading and writing files

1. File operations yl

Four groups of document processing operations: open, close, read, write.

  • open () to open the file
  • close () closes the file
  • String read () returns the contents of the file saved in
  • readline () to get a list of strings from the file, list each string is specified in each line of text
  • open (filename, 'w') to write the file, write-mode (overwrites the original content)
  • open (filename, 'a') written to the file, using the additive mode (add content to the end of an existing file)

Among them, should be noted that if passed to open () the file name does not exist, write mode and append mode will create a new, empty file.

Code demonstrates:

helloFile = open(r'E:\【05】编程设计\Python\Python自动化办公\【08】读写文件\hello.txt')

text = helloFile.read()
print(text)

content = helloFile.readlines()
print(content)

baconFile = open('大家好.txt','w')
baconFile.write('你好鸭,')
baconFile = open('大家好.txt','a')
baconFile.write('我很好鸭!')
baconFile.close()
baconFile = open('大家好.txt')
print(baconFile.read())

Output:
Here Insert Picture Description
Here Insert Picture Description
-

2.shelve module saves variables

We can use Python shelve module will save the program variables to the binary file shelf in order to achieve the program can recover data from the hard disk of variables.

Code demonstrates:

import shelve

shelfFile = shelve.open('mydata')   # 打开(创建)shelf文件
cats = ['英短','加菲','布偶']
shelfFile['cats'] = cats                # 保存变量
shelfFile.close()

shelfFile = shelve.open('mydata')
print(type(shelfFile))                # 打印文件类型
print(list(shelfFile.keys()))        # 打印键
print(list(shelfFile.values()))     # 打印值

Output:
Here Insert Picture Description

Here Insert Picture Description
Here Insert Picture Description

Published 35 original articles · won praise 35 · views 2741

Guess you like

Origin blog.csdn.net/nilvya/article/details/104312454