Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of dealing with Python files and directories

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Python files and directory processing methods have", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in-depth, together to study and learn "Python files and directories processing methods are what" it!

I. directory operation

1. Get the current code path

Test_folder.pyimport osimport sysprint (_ _ file__) print (sys.argv [0]) print (os.path.realpath (_ _ file__)) print (os.path.abspath (sys.argv [0]))

Out:

D:/ProgramWorkspace/PythonNotes/03-File-Handling/test_folder.py

D:/ProgramWorkspace/PythonNotes/03-File-Handling/test_folder.py

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling\ test_folder.py

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling\ test_folder.py

two。 Get the directory of the current file _ _ file__

Print (os.getcwd ()) print (os.path.dirname (os.path.realpath (_ _ file__) print (os.path.split (os.path.realpath (_ _ file__)) [0]) path = os.path.dirname (os.path.realpath (_ _ file__))

Out:

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling

3. Get the current file name

Print (os.path.basename (sys.argv [0])) # current file name print (os.path.basename (_ _ file__))

Out:

Test_folder.py

Test_folder.py

4. Splicing path

Path = os.path.dirname (os.path.realpath (_ _ file__)) filename = os.path.basename (_ _ file__) abspath = os.path.join (path, filename) print (abspath)

Out:

D:\ ProgramWorkspace\ PythonNotes\ 03-File-Handling\ test_folder.py

5. Create a directory

Determine if the directory exists:

Os.path.exists (path)

Create a directory:

If not os.path.exists (path): print (f "create folder: {path}") os.makedirs (path) II. File operation

1. Create a text file

Text = "Hello World!" newfilepath = os.path.join (path, "newfile.txt") file = open (newfilepath,'w') file.write (text) # write content information file.close () 2. Determine whether the file exists or not

Print (os.path.isfile (path)) print (os.path.isfile (newfilepath)) print (os.path.exists (newfilepath))

Out:

False

True

True

Os.path.isfile is used to determine whether it is a file and whether it exists, and os.path.exists can also be used to determine whether a file exists, but it is still recommended to use os.path.isfile to judge a file, and os.path.exists to determine whether a directory exists. For example, if a file is newfile, using both methods will return True, and it is impossible to tell whether it is a file or a directory.

3. Judge file attributes

Print (os.access (newfilepath,os.F_OK)) # whether the file exists print (os.access (newfilepath,os.R_OK)) # whether the file is readable print (os.access (newfilepath,os.W_OK)) # whether the file can be written to print (os.access (newfilepath,os.X_OK)) # whether the file has execution permission

Out:

True

True

True

True

Os.access (newfilepath,os.F_OK) can also be used to determine whether a file exists.

4. Open a file

You can use the open () method to open a text file or binary file:

F = open (filename, mode)

Several file opening modes:

B: binary mode

T: text mode (default)

R: open the existing file, read operation (default).

W: open the file, write, and the contents of the previous file will be deleted. If the file does not exist, it will be created automatically.

A: open the file, append the operation, will not delete the contents of the previous file. If the file does not exist, it will be created automatically.

X: create a new file, write operation, use this mode to open an existing file will throw an exception.

R +: read and write operations, will not delete the contents of the previous file, but will overwrite the content.

W +: write and read operations, which delete the contents of the previous file.

A +: append, read operations, will not delete and overwrite the contents of the previous file.

X +: create new files, read and write operations.

The default mode of the open () method is rt mode, which is to read text files.

In addition, you need to pay attention to how to write filename, for example, the file path is D:\ test.txt, where\ t may be escaped and you need to add an r from the front:

F = open (r "D:\ test.txt", "w") 5. Write a file

Both reading and writing files need to open the file first, return a file object, and then read and write to the file object. Write permissions need to be set to write files, such as w, w +, a modes.

There are two main ways to write a file:

File.write (str): writing a string

File.writelines (list): writes a list of strings for inserting multiple strings at the same time.

Take a chestnut:

File = open ("newfile.txt",'w') text1 = "Hello World!\ nHello, world!\ r" file.write (text1) # write content information text2 = ["To the time to life,\ n", "rather than to life in time.\ r"] file.writelines (text2) file.close ()

W mode deletes the contents of the previous file. If you don't want to delete it, you need to append it directly. You can use an and a + modes:

File = open ("newfile.txt",'a') 6. Read the file

There are several common ways to read files:

In operator

Read (): reads all the data and returns a string.

Readline (): read the first line

Readlines (): reads all rows, each saved as an element of the list.

# Open and read the file file = open ("newfile.txt",'r') for line in file: print (line) print () file.seek (0,0) print (file.read (5)) # print () file.seek (0,0) print (file.readline (12) print () file.seek (0,0) print (file.readlines ()) print () file.close ()

Execution result:

Hello World! Hello, World! To the time to life, rather than to life in time.HelloHello World! ['Hello World!' Hello, World! \ To the time to life, 'rather than to life in time.\ n']

After reading all the contents of the file object, the cursor of the text moves to the end. To read the file again, you need to move the cursor to the front. Use the file.seek (0,0) method to move the cursor to the front. Another solution is to store the read in a local variable.

7. With statement

With statements can be used for exception handling to ensure proper acquisition and automatic release of resources. After using the with statement, there is no need to call the file.close () statement, it is automatically released.

Text1 = "Hello World!\ nHello, World!\ r" text2 = ["To the time to life,\ n", "rather than to life in time.\ r"] # write with open ("newfile.txt", "w") as file: file.write (text1) file.writelines (text2) # read with open ("newfile.txt", "r +") as file: print (file.read ())

With statements are very useful for dealing with large files, such as 10G files, and with statements manage the context.

Thank you for your reading, the above is the "Python file and directory processing methods have what" the content, after the study of this article, I believe you have a deeper understanding of the Python file and directory processing methods have a more profound understanding, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report