Python文件操作的介绍(代码示例)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python文件操作的介绍(代码示例),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1497字,纯文字阅读大概需要3分钟。
内容图文
![Python文件操作的介绍(代码示例)](/upload/InfoBanner/zyjiaocheng/429/429e968e620049a09fea9f7156639db7.jpg)
本篇文章给大家带来的内容是关于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文件操作的介绍(代码示例)的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的Python文件操作的介绍(代码示例)全部内容,希望文章能够帮你解决Python文件操作的介绍(代码示例)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。