Python中如何优雅地处理文件和目录操作的问题实例

原创 矫情吗;* 2025-02-25 02:54 90阅读 0赞

在Python中,我们可以使用标准库或者第三方库来优雅地处理文件和目录操作。以下是一些实例:

  1. 创建新文件

    1. with open('new_file.txt', 'w') as file:
    2. file.write('Hello, new file!')
  2. 读取现有文件内容

    1. with open('existing_file.txt', 'r') as file:
    2. content = file.read()
    3. print(content)
  3. 创建目录(如果不存在):

    1. import os
    2. directory_path = '/new/directory'
    3. if not os.path.exists(directory_path):
    4. os.makedirs(directory_path)
    5. print(f'Created directory: {directory_path}')
    6. else:
    7. print(f'Directory already exists: {directory_path}')

以上就是使用Python优雅地处理文件和目录操作的一些实例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读