python读写文件通过open函数来完成
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
![](https://i-blog.csdnimg.cn/blog_migrate/8c32cf9673a589dd3bfb87c03fda992e.png)
#python创建文件
from pathlib import Path
def filecreate():
filePath="E:\\test\\python\\example.txt"
if os.path.exists(filePath)==False:
# 方法一:使用open函数和'w'模式(写模式)创建文件:
with open(filePath, 'w') as file:
file.write("Hello, World!")
#使用with会自动关闭,不用再手动写close,file.close()
# 方法二:使用open函数和'x'模式(独占创建模式)创建文件:
try:
with open(filePath, 'x') as file:
file.write("Hello, World!")
print(file.read())
except FileExistsError:
print("文件已存在")
with open(filePath, 'r') as file:
print(file.read())
# 方法三:使用pathlib模块创建文件:
try:
# 创建一个名为example.txt的文件
Path("E:\\test\\python\\example1.txt").touch()
except FileExistsError:
print("文件已存在1")
#python合并文件
def combineFile():
with open("E:\\test\\python\\example1.txt") as file1:
fileData1=file1.read()
with open("E:\\test\\python\\example2.txt") as file2:
fileData2=file2.read()
with open("E:\\test\\python\\exampleNew.txt", mode="w",encoding="utf-8") as fileNew:
fileNew.write(fileData1+"\n")
fileNew.write(fileData2)
'''
python判断文件编码,然后以原先的编码打开文件
chardet 是第三方库,需要通过 pip 命令为 Python 安装后使用
pip3 install chardet
'''
from chardet.universaldetector import UniversalDetector
def fileformat():
detector = UniversalDetector()
with open("E:\\test\\python\\exampleNew.txt", "rb") as f:
detector.feed(f.read())
detector.close()
print(detector.result)
#输出 {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
#原先指定了utf-8,再使用gbk打开就会报错 'gbk' codec can't decode byte 0x8c
with open("E:\\test\\python\\exampleNew.txt", mode='r',encoding='utf-8') as fileNew:
print(fileNew.read())
# 文件重新命名
old_filename="E:\\test.txt"
new_filename="E:\\testNew.txt"
os.rename(old_filename, new_filename)
#复制文件
with open(srcFilePath, 'rb') as src, open(destFilePath, 'wb') as dest:
dest.write(src.read())
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
combineFile()
fileformat()