本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python文件操作的相关知识介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、文件操作
1-1 遍历文件夹和文件
1 2 3 4 5 6 7 8 9 10 11 12 | 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 获取文件名和扩展名
1 2 3 4 5 6 | 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 逐行读取文本文件内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 写文件
1 2 3 4 5 | 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 判断文件是否存在
1 2 3 4 5 6 7 | 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 创建文件夹
1 2 3 4 5 6 7 | import os
# Make multilayer directorys
os.makedirs( "/path/to/dir" )
# Make single directory
os.makedir( "/path/to/dir" )
|
以上就是Python文件操作的介绍(代码示例)的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
实例分析Python跨文件全局变量的实现方法
Python的collection模块
Python操作mongodb的9个步骤
Python之调度器的用法
Python中flask蓝图的使用方法(附代码)
Python import是什么
Python支持返回函数的实例解析
Python中reload用法实例
pycharm怎么安装
简介Python的sklearn机器学习算法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python文件操作的介绍(代码示例)