"Python" Read and Write Files

Posted by bubblocity on Thu, 03 Feb 2022 18:25:50 +0100

Author: An Engineering Engineer in AXYZdong Automation
Have a little thought, a little thought, a little reason!
Set a small goal and work hard to become a habit! Meet a better self in the most beautiful years!
CSDN@AXYZdong , CSDN launch, original AXYZdong
The only blog update address is: 👉 AXYZdong's Blog 👈
The home page of Station B is: AXYZdong's Personal Home Page

File and File Path

Two key properties of a file: the file name and path, which represent the location of the file on your computer

On Windows, the path is written using a backslash\ as the separator between folders

On OS X and Linux, use forward slash / as the path separator.

Current working directory

Every program running on a computer has a Current Working Directory, or cwd. No file name or path from the root folder is assumed to be in the current working directory. Os. The getcwd() function takes a string of the current working path and can take advantage of os.chdir() changes it.

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

Absolute and relative paths

  • Absolute path: Always start from the root folder.
  • Relative path: relative to the program's current working directory.


Use os.makedirs() create a new folder

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

os.makedirs('.\read1'): A relative path to create a read1 folder in the current working directory.

os.makedirs('D:\Python study\read2'): absolute path, create read2 folder under Python Study folder on D drive.

To ensure the full path name exists, if the intermediate folder does not exist, os.makedirs() will create all necessary intermediate folders.

os.path module

Os. The path module contains many useful functions related to file names and file paths. Os. Path is a module in the OS module, and import os can import it. Os. Complete documentation for the path module: http://docs.python.org/3/library/os.path.html .

Processing absolute and relative paths

  • os.path.abspath(path) returns a string of absolute paths for parameters, facilitating the conversion of relative paths to absolute paths.
  • os.path.isabs(path) determines whether the parameter is an absolute path, returns True if it is, or returns False if it is not.
  • os.path.relpath(path,start) returns a string of relative paths from start to path, and defaults to the current working directory as the start path if no start is provided.
  • os.path.dirname(path) returns a string containing everything before the last slash in the path parameter. (that is, return the directory name)
  • os.path.basename(path) returns a string containing everything after the last slash in the path parameter. (that is, return the base name)
  • os.path.split(path) returns both the directory name and the base name of a path to get tuples containing both 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) returns the size of the folder under the path path path.
  • os.listdir(path) returns a list of file name strings under the path path 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', 'Crawl Pictures.py', 'veil.jpg']

Check the validity of the path

  • os.path.exists(path) determines whether the file or folder specified by the path parameter exists, returns True if it exists, or False if it does not.
  • os.path.isfile(path) determines if the path parameter is a file and returns True if it is, otherwise returns False.
  • os.path.isdir(path) determines if the path parameter is a folder and returns True if it is, or False if it is not.
>>>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. The exists() function determines whether a DVD or flash drive is currently connected to the computer. (I don't currently have an F drive on my computer)

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

File Read-Write Process

Plain text file: Contains only basic text characters, not font, size, and color information. For example: with. Text file with txt extension, with. Python script file with py extension.

Three steps to read and write a file:

  1. Call the open() function to return a File object.
  2. Call the read() or write() method of the File object.
  3. Call the close() method of the File object to 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 one in the current directory. TXT text file and then 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

Save variables with shell module

Use the shell module to save variables from a Python program to a binary shell file.

Steps:

  1. import shelve
  2. Call the function shelve.open() and pass in a file name, then save the return value (shell value) in a variable. (You can modify the shell value of this variable, just like a dictionary)
  3. Call the close() method on the returned object

shelve.open() Open files are read and write by default, and like a dictionary, shelf values have keys() and values() methods that return keys and values in a shell.

Use pprint. The pformat() function holds the variable and writes it. py file

Where to use: Suppose you have a dictionary stored in a variable and you want to save the variable and its contents, then you can use pprint. The pformat() function saves this variable and writes it to. py file. This file becomes a module that can be called when needed.

>>>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'

This way, there will be a character in the current working directory. Py file with only one line of code characters = {'one':'a','two':'b'}

Create one. The benefit of Py files is that. The py file is a text file that anyone can read and modify using a simple text editor.

Reference

[1]: Quick start with Python programming: Automating tedious work / by A1 Sweigart; Wang Haipeng Translated. Beijing: People's Posts and Telecommunications Press, 2016.7

_This is where we share

If my blog is helpful to you and if you like my blog content, please "compliment", "collection", "concern" one click three times!

More exciting content please go AXYZdong's Blog

If there are any errors or inaccuracies in the above, welcome to the following 👇 Leave a message. Or you have a better idea, welcome to communicate and learn ~~

Topics: Python