首頁  >  文章  >  後端開發  >  Python檔案操作的介紹(程式碼範例)

Python檔案操作的介紹(程式碼範例)

不言
不言轉載
2019-02-22 14:43:411927瀏覽

本篇文章帶給大家的內容是關於Python文件操作的相關知識介紹(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。

1、檔案操作

1-1 遍歷資料夾與檔案

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

1-2 取得檔案名稱與副檔名

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

1-3 逐行讀取文字檔案內容

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)

1-4 寫入檔案

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

output.write(all_the_text)
# output.writelines(list_of_text_strings)

1-5 判斷檔案是否存在

import os

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

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

1-6 建立文件夾

import os

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

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

以上是Python檔案操作的介紹(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除