python写入txt,读取txt,拷贝txt文件

以下代码为
1:新建onefile.txt文件
2:向onefile.txt文件中写入数据
3:尝试读取新建文件的所有数据
4:尝试读取该文件指定数据
5:拷贝onefile.txt至新建twofile.txt文件,并且统计行数与字节长度

下面该代码为第1,2,3,4
把代码复制,并创建test.py文件,然后在当前文件夹中的终端执行python3 test.py即可

# 打开文件,并且写入6.2文件的基本处理
def main():
    # 第一步打开文件
    # 打开文件open()
    # <variable> = open(<name磁盘文件名>,<mode打开模式>)
    onefile = open("onefile.txt","w") #  打开一个文件onefile.txt,没有则创建w
    # r 只读,不存在则报错
    # w 只写,不存在则创建
    # a 表示附加到文件末尾
    # rb 只读二进制文件,文件不存在则报错
    # wb 只写 二进制文件,文件不存在则创建
    # ab 附加到二进制文件末尾
    # r+ 读写
    # 第二步文件读取/写入
    onefile.write("字符串\n")
    onefile.writelines(["Hello"," ","world","\n"]) #  写入文件内容为列表格式
    onefile.writelines(["Hello"," ","lui","\n"]) #  写入文件内容为列表格式
    onefile.writelines(["Hello"," ","chun"]) #  写入文件内容为列表格式
    # write()把含有文本数据或二进制数据块的字符串写入文件中
    # writelines()针对列表操作,接收一个字符串列表作为参数,将它们写入文件中
    # 第三步关闭保存文件
    onefile.close() # 关闭文件
    # 第四步重新打开文件
    openonefile =open("onefile.txt","r")# 打开上面创建的onefile,大开方式为只读
    # 第五步读取文件
    data = openonefile.read()
    # 读取展示为read()返回值为包含整个文件内容的一个字符串
    # readline()返回值为文件下一行内容的字符串
    # readlines()f返回值为整个文件内容的列表,每项是以换行符结尾的一行字符串
    # 第六步输出文件
    print(data) 
    # 第七步关闭文件
    onefile.close()
    print("展示案例仅展示本文档指定前两行")
    # 案例展示 仅仅读取前两行
    twofile = open("onefile.txt","r")
    for i in range(2):
        line = twofile.readline()
        print(line[:-1])
    onefile.close()
# 调用上方设置的函数
main()

以下代码为第5
把代码复制,并创建test.py文件,然后在当前文件夹中的终端执行python3 test.py即可
在这里插入图片描述

def main():
    # 输入文件名
    f1 = input("请输入文件名(需要拷贝的文件):").strip()
    f2 = input("请为新拷贝的文件命名:").strip()
    # 打开文件
    onefile = open(f1, "r") #打开方式
    twofile = open(f2,"w")
    # 拷贝数据
    countLines = countChars =0
    for line in onefile.readlines():
        countLines += 1 #统计复制的行数
        countChars += len(line) #统计所有字符串长度
        twofile.write(line)
    print(countLines,"lines and",countChars,"chars copied")
    onefile.close()
    twofile.close()
# 调用上方设置的函数
main()

猜你喜欢

转载自blog.csdn.net/weixin_47021806/article/details/113933837