如何在Python中实现文件操作?包括读写、复制、删除等常见操作

原创 偏执的太偏执、 2025-02-04 23:51 61阅读 0赞

在Python中,我们可以使用内置的open()函数来进行各种文件操作。下面是一些常见的操作:

  1. 读取文件内容

    1. # 打开文件并以文本模式读取
    2. with open('filename.txt', 'r') as file:
    3. content = file.read() # 获取全部内容
    4. print(content) # 输出到控制台
  2. 写入文件内容
    ```python

    打开文件,以写入模式创建(如果不存在)

    with open(‘newfile.txt’, ‘w’) as file:
    file.write(‘Hello, world!’) # 写入指定内容

也可以使用’a’模式追加内容

with open(‘newfile.txt’, ‘a’) as file:
file.write(‘\nThis is an appended line.’)

  1. 3. **复制文件**:
  2. ```python
  3. import shutil
  4. # 源文件
  5. source_file = 'sourcefile.txt'
  6. # 目标文件夹(如果不存在则创建)
  7. target_folder = 'destinationfolder'
  8. # 使用shutil模块的copy2()函数进行复制操作,确保目标文件存在
  9. if not os.path.exists(target_folder)):
  10. os.makedirs(target_folder)
  11. shutil.copy2(source_file, os.path.join(target_folder, source_file.split('/')[-1])))
  12. print(f'Successfully copied {source_file} to {target_folder}.'))
  1. 删除文件或文件夹
    ```python

    文件

    file_to_delete = ‘filename.txt’

文件夹(如果存在则删除)

folder_to_delete = ‘destinationfolder’

if os.path.exists(file_to_delete)):
os.remove(file_to_delete))

if os.path.exists(folder_to_delete)):
shutil.rmtree(folder_to_delete))

print(f’Successfully deleted {file_to_delete if os.path.exists(file_to_delete)) else “File does not exist”} and {folder_to_delete if os.path.exists(folder_to_delete)) else “Folder does not exist”} from their locations.’)
```

以上就是Python中实现文件操作的一些基本方法。

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

发表评论

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

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

相关阅读