Python文件操作的介绍(代码示例)
本篇文章给大家带来的内容是关于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中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

Python参数注解的另类用法在Python编程中,参数注解是一种非常有用的功能,可以帮助开发者更好地理解和使用函...

Python脚本如何在特定位置清空输出到光标位置?在编写Python脚本时,如何清空之前的输出到光标位置是个常见的...

使用Python破解验证码的探索在日常的网络交互中,验证码是一种常见的安全机制,用以防止自动化程序的恶意操...

Python入门:沙漏图形绘制及输入校验本文将解决一个Python新手在沙漏图形绘制程序中遇到的变量定义问题。代码...

使用requests库抓取网页数据时遇到的问题及解决方案在使用Python的requests库获取网页数据时,有时会遇到获取到�...

如何利用Go或Rust调用Python脚本实现真正的并行执行?最近在使用Python...
