python文件读写

创建文件并写入字符串

# 创建文件并写入字符串
file = open("cau.txt", 'w')
str = "Hello China Agricultural university!"
file.write(str)
file.close()
文件cau.txt内容:
Hello China Agricultural university!

读文件

# 读文件
with open("cau.txt", 'r') as f:  # 自动关闭文件
    s1 = f.read(10)  # 读取前10个字符
    s2 = f.read()  # 读取剩余字符
    f.seek(0)  # 文件指针回退到文件开头
    s3 = f.read()  # 读取
    print("s1:", s1)
    print("s2:", s2)
    print("s3:",s3)
输出结果:
# s1: Hello Chin
# s2: a Agricultural university!
# s3: Hello China Agricultural university!
上一篇:Solution -「Gym 102956A」Belarusian State University


下一篇:7-1 字符串替换 (10 分)