如何在Python中实现文件操作?包括读写、复制、删除等常见操作
在Python中,我们可以使用内置的open()
函数来进行各种文件操作。下面是一些常见的操作:
读取文件内容:
# 打开文件并以文本模式读取
with open('filename.txt', 'r') as file:
content = file.read() # 获取全部内容
print(content) # 输出到控制台
写入文件内容:
```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.’)
3. **复制文件**:
```python
import shutil
# 源文件
source_file = 'sourcefile.txt'
# 目标文件夹(如果不存在则创建)
target_folder = 'destinationfolder'
# 使用shutil模块的copy2()函数进行复制操作,确保目标文件存在
if not os.path.exists(target_folder)):
os.makedirs(target_folder)
shutil.copy2(source_file, os.path.join(target_folder, source_file.split('/')[-1])))
print(f'Successfully copied {source_file} to {target_folder}.'))
文件夹(如果存在则删除)
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中实现文件操作的一些基本方法。
还没有评论,来说两句吧...