Introduction to Python file operations (code examples)

不言
Release: 2019-02-22 14:43:41
forward
1993 people have browsed it

The content of this article is an introduction to relevant knowledge about Python file operations (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. File operation

1-1 Traverse folders and files

import os
rootDir = "/path/to/root"

for parent, dirnames, filenames in os.walk(rootDir):
    for dirname in dirnames:
        print("parent is:" + parent)
        print("dirname is:" + dirname)
    
    for filename in filenames:
        print("parent is:" + parent)
        print("filename is:" + filename)
        print("the full name of the file is:" + os.path.join(parent, filename))
Copy after login

1-2 Get the file name and extension

import os
path = "/root/to/filename.txt"
name, ext = os.path.splitext(path)
print(name, ext)
print(os.path.dirname(path))
print(os.path.basename(path))
Copy after login

1-3 Read the text file content line by line

f = open("/path/to/file.txt")

# The first method
line = f.readline()
while line:
    print(line)
    line = f.readline()
f.close()

# The second method
for line in open("/path/to/file.txt"):
    print(line)

# The third method
lines = f.readlines()
for line in lines:
    print(line)
Copy after login

1-4 Write the file

output = open("/path/to/file", "w")
# output = open("/path/to/file", "w+")

output.write(all_the_text)
# output.writelines(list_of_text_strings)
Copy after login

1-5 Determine whether the file exists

import os

os.path.exists("/path/to/file")
os.path.exists("/path/to/dir")

# Only check file
os.path.isfile("/path/to/file")
Copy after login

1-6 Create the file Clip

import os

# Make multilayer directorys
os.makedirs("/path/to/dir")

# Make single directory
os.makedir("/path/to/dir")
Copy after login

The above is the detailed content of Introduction to Python file operations (code examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!