Python write txt, read txt, copy txt file

The following code is
1: Create new onefile.txt file
2: Write data to onefile.txt file
3: Try to read all data of the newly created file
4: Try to read the specified data of the file
5: Copy onefile.txtto the newly created twofile.txtfile, and count the lines Number and byte length

The following code for the first 1,2,3,4item
to copy the code, and create test.pyfiles in the current folder and then the terminal of execution python3 test.pycan

# 打开文件,并且写入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()

The following code is the first 5item
to copy the code and creates test.pythe file, and then execute the terminal in the current folder python3 test.pycan be
Insert picture description here

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

Guess you like

Origin blog.csdn.net/weixin_47021806/article/details/113933837