python学习(一):读写文件

python读写文件通过open函数来完成

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open

#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()

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值