Python基础---文件的读写

例1 将字符串写入指定文件中

def main():
    # 打开桌面文件name.txt(如果该文件不存在,则创建;如果已存在,则删除文件内容),创建文件对象file_1
    file_1 = open(r'C:\Users\yyf24\Desktop\name.txt', 'w')

    # 将字符串写入文件中
    file_1.write('Zoe\n')
    file_1.write('YYF\n')
    file_1.write('BWQ\n')

    # 关闭文件
    file_1.close()


main()

在这里插入图片描述
在这里插入图片描述

例2 读取文件

def main():

    file_1 = open(r'C:\Users\yyf24\Desktop\name.txt', 'r')

    # 读取file_1中第一行,以字符串形式赋值于file_line_1
    # file_1.readline()返回值带\n(换行符)
    file_line_1 = file_1.readline()

    # 去除file_1.readline()返回值中的换行符
    file_line_2 = file_1.readline().rstrip('\n')
    
    # 读取file_1中的内剩余内容,以字符串形式赋值于file_content
    file_content = file_1.read()

    print(file_line_1)
    print(file_line_2)
    print(file_content)

    file_1.close()


main()

在这里插入图片描述

例3 为文件增加内容

def main():

    file_1 = open(r'C:\Users\yyf24\Desktop\name.txt', 'a')

    file_1.write('小龙女\n')
    file_1.write('鸠摩智\n')
    file_1.write('段誉\n')

    file_1.close()


main()

在这里插入图片描述

例4 使用for循环写入文件

def main():

    file_1 = open(r'C:\Users\yyf24\Desktop\books.txt', 'w')

    num = int(input("您要输入几本秘籍? "))

    for n in range(1, num+1):

        file_1.write(input("请输入第" + str(n) + "本秘籍: ") + '\n')

    file_1.close()
    print(str(num) + "本秘籍已输入完成!")


main()

在这里插入图片描述

在这里插入图片描述

例5 使用while循环读取文件

def main():

    file_1 = open(r'C:\Users\yyf24\Desktop\books.txt', 'r')

    line = file_1.readline().rstrip()

    while line != '':

        print(line)

        line = file_1.readline().rstrip()

    file_1.close()


main()

在这里插入图片描述

例6 使用for循环读取文件

def main():

    file_1 = open(r'C:\Users\yyf24\Desktop\books.txt', 'r')

    for line in file_1:

        print(line, end='')

    file_1.close()


main()

在这里插入图片描述

练习1

Kevin is a freelance video producer who makes TV commercials for localbusinesses. When he makes a commercial, he usually films several short videos. Later, he puts these short videos together to make the final commercial. He has asked you to write the following two programs.

  1. A program that allows him to enter the running time (in seconds) of each short video in a project. The running times are saved to a file.
  2. A program that reads the contents of the file, displays the running times, and then displays the total running time of all the segments.

提示用户将视频的每段的时长(单位:秒,精确到小数点后两位)写入文件

Here is the general algorithm for the first program, in pseudocode:
Get the number of videos in the project.
Open an output file.
For each video in the project: Get the video’s running time.
Write the running time to the file.
Close the file.

def main():

    num = int(input("请输入视频数:"))

    file_1 = open(r'C:\Users\yyf24\Desktop\video.txt', 'w')

    for n in range(1, num+1):

        file_1.write(input("请输入第" + str(n) + "段视频的长度(秒): ") + '\n')

    file_1.close()
    print(str(num) + "段视频长度已输入完成!")


main()

在这里插入图片描述

在这里插入图片描述

读取文件内容,显示每段视频长度即视频总时长

Here is the general algorithm for the second program:
Initialize an accumulator to 0.
Initialize a count variable to 0.
Open the input file.
For each line in the file: Convert the line to a floating-point number. (This is the running time for a video.)
Add one to the count variable. (This keeps count of the number of videos.)
Display the running time for this video.
Add the running time to the accumulator.
Close the file.
Display the contents of the accumulator as the total running time.

def main():
    accumulator = 0
    count = 0

    file_1 = open(r'C:\Users\yyf24\Desktop\video.txt', 'r')

    for line in file_1:

        run_t = float(line)

        count += 1
        accumulator += run_t

        print("第" + str(count) + "段视频长度为" + str(format(run_t, '.2f')) + "秒;")

    file_1.close()

    print("视频总长度为" + str(accumulator) + "秒")


main()

在这里插入图片描述

例7 创建一个学生记录文件,包括姓名、年龄、专业

def stu_record_write():

    num = int(input("一共要输入多少个学生? "))

    file_1 = open(r'C:\Users\yyf24\Desktop\students.txt', 'w')

    for n in range(1, num+1):
        print("请输入第" + str(n) +"个学生的信息!")

        name = input("姓名: ")
        age = input("年龄: ")
        major = input("专业: ")

        file_1.write(name + '\n')
        file_1.write(age + '\n')
        file_1.write(major + '\n')

        print()

    file_1.close()

    print("学生信息输入完毕!")


stu_record_write()

例8 读取学生记录文件

def stu_record_read():

    file_1 = open(r'C:\Users\yyf24\Desktop\students.txt', 'r')

    name = file_1.readline().rstrip()
    count = 1

    while name != '':
        age = file_1.readline().rstrip()
        major = file_1.readline().rstrip()

        print("第" + str(count) + "个学生的信息:")
        print("姓名:" + name)
        print("年龄:" + age)
        print("专业:" + major)

        name = file_1.readline().rstrip()
        count += 1

    file_1.close()

    print("学生信息输出完毕!")


stu_record_read()

练习

Midnight Coffee Roasters, Inc. is a small company that imports raw coffee beans from around the world and roasts them to create a variety of gourmet coffees.
Julie, the owner of the company, has asked you to write a series of programs that she can use to manage her inventory.
After speaking with her, you have determined that a file is needed to keep inventory records.
Each record should have two fields to hold the following data:
• Description. A string containing the name of the coffee
• Quantity in inventory. The number of pounds in inventory, as a floating-point number

Your first job is to write a program that can be used to add records to the file.

def coffee_record_add():

    flag = 'y'

    file_1 = open(r'C:\Users\yyf24\Desktop\coffee.txt', 'a')

    while flag == 'y' or flag == 'Y':

        description = input("请输入咖啡的种类:")
        quantity = input("请输入咖啡的重量:")

        file_1.write(description + '\n')
        file_1.write(quantity + '\n')

        flag = input("继续输入请按y,否则请按任意键:")


    file_1.close()

    print("输入完毕!")


coffee_record_add()

Your next job is to write a program that displays all of the records in the inventory file.
def coffee_record_read_v1():

    file_1 = open(r'C:\Users\yyf24\Desktop\coffee.txt', 'r')

    count = 1
    description = file_1.readline().rstrip()

    while description != '':

        quantity = file_1.readline().rstrip()

        print("存量" + str(count))
        print("咖啡种类: " + description)
        print("重量(磅): " + quantity)

        count += 1
        description = file_1.readline().rstrip()

    file_1.close()
    print("输出完毕!")


coffee_record_read_v1()

Julie has been using the first two programs that you wrote for her.
She now has several records stored in the coffee.txt file and has asked you to write another program that she can use to search for records.
She wants to be able to enter a description and see a list of all the records matching that description.

def coffee_record_search_v1():

    search = input("请输入您要搜索的咖啡种类:")

    file_1 = open(r'C:\Users\yyf24\Desktop\coffee.txt', 'r')

    flag = False

    description = file_1.readline().rstrip()

    while description != '':

        quantity = file_1.readline().rstrip()

        if description == search:
            print("咖啡的种类:", description)
            print("存量:", quantity)
            print()

            flag = True

        description = file_1.readline().rstrip()

    file_1.close()

    if not flag:
        print("您搜索的咖啡种类不存在!")


coffee_record_search_v1()

Your next job is to write a program that she can use to modify the quantity field in an existing record.
This will allow her to keep the records up to date as coffee is sold or more coffee of an existing type is added to inventory.
To modify a record in a sequential file, you must create a second temporary file.
You copy all of the original file’s records to the temporary file, but when you get to the record that is to be modified, you do not write its old contents to the temporary file.
Instead, you write its new modified values to the temporary file.
Then, you finish copying any remaining records from the original file to the temporary file.
The temporary file then takes the place of the original file.
You delete the original file and rename the temporary file, giving it the name that the original file had on the computer’s disk.
Here is the general algorithm for your program.
Open the original file for input and create a temporary file for output.
Get the description of the record to be modified and the new value for the quantity.
Read the first description field from the original file.
While the description field is not empty: Read the quantity field.
If this record ’s description field matches the description entered: Write the new data to the temporary file. Else: Write the existing record to the temporary file.
Read the next description field.
Close the original file and the temporary file.
Delete the original file. Rename the temporary file, giving it the name of the original file.

> Open the original file for input and create a temporary file for output.

> Get the description of the record to be modified and the new value for the quantity.

> Read the first description field from the original file.

> While the description field is not empty: Read the quantity field.

> If this record ’s description field matches the description entered:

Write the new data to the temporary file. Else: Write the existing record to the temporary file.

> Read the next description field.

> Close the original file and the temporary file.

import os


def coffee_record_modify():

    flag = False

    file_coffee = open(r'C:\Users\yyf24\Desktop\coffee.txt', 'r')
    file_temp = open(r'C:\Users\yyf24\Desktop\temp.txt', 'w')

    search = input("请输入您要修改的咖啡种类:")

    description = file_coffee.readline().rstrip()

    while description != '':

        quantity = file_coffee.readline().rstrip()

        if description == search:
            modify_quantity = input("当前给种类咖啡的存量(磅):")
            file_temp.write(description + '\n')
            file_temp.write(modify_quantity + '\n')
            flag = True
        else:
            file_temp.write(description + '\n')
            file_temp.write(quantity + '\n')

        description = file_coffee.readline().rstrip()

    file_coffee.close()
    file_temp.close()

    os.remove(r'C:\Users\yyf24\Desktop\coffee.txt')
    os.rename(r'C:\Users\yyf24\Desktop\temp.txt', r'C:\Users\yyf24\Desktop\coffee.txt')

    if flag:
        print("修改完成!")
    else:
        print("您所要修改的咖啡种类不存在!")


coffee_record_modify()

Your last task is to write a program that Julie can use to delete records from the coffee.txt file.
Like the process of modifying a record, the process of deleting a record from a sequential access file requires that you create a second temporary file.
You copy all of the original file’s records to the temporary file, except for the record that is to be deleted.
The temporary file then takes the place of the original file.
You delete the original file and rename the temporary file, giving it the name that the original file had on the computer’s disk.
Here is the general algorithm for your program.
Open the original file for input and create a temporary file for output.
Get the description of the record to be deleted.
Read the description field of the first record in the original file.
While the description is not empty: Read the quantity field.
If this record’s description field does not match the description entered: Write the record to the temporary file.
Read the next description field.
Close the original file and the temporary file.
Delete the original file.
Rename the temporary file, giving it the name of the original file.

> Open the original file for input and create a temporary file for output.

> Get the description of the record to be deleted.

> Read the description field of the first record in the original file.

> While the description is not empty: Read the quantity field.

> If this record’s description field does not match the description entered: Write the record to the temporary file.

> Read the next description field.

> Close the original file and the temporary file.

> Delete the original file.

> Rename the temporary file, giving it the name of the original file.

import os

def coffee_record_delete():

    flag = False

    file_coffee = open(r'C:\Users\yyf24\Desktop\coffee.txt', 'r')
    file_temp = open(r'C:\Users\yyf24\Desktop\temp.txt', 'w')

    search = input("请输入您要修改的咖啡种类:")

    description = file_coffee.readline().rstrip()

    while description != '':

        quantity = file_coffee.readline().rstrip()

        if description != search:
            file_temp.write(description + '\n')
            file_temp.write(quantity + '\n')
        else:
            flag = True

        description = file_coffee.readline().rstrip()

    file_coffee.close()
    file_temp.close()

    os.remove(r'C:\Users\yyf24\Desktop\coffee.txt')
    os.rename(r'C:\Users\yyf24\Desktop\temp.txt', r'C:\Users\yyf24\Desktop\coffee.txt')

    if flag:
        print("删除完成!")
    else:
        print("没有找到需要删除的咖啡种类!")


coffee_record_delete()

参考文献
[1] Tony Gaddis,Starting Out with Python[M],United Kingdom: Pearson,2019

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值