Python -读取,存储文件

本文介绍Python中文件的基本操作,包括读取、写入、从控制台输入保存至文件及文件内容的处理等。通过实例演示如何进行文件内容的读取、处理及输出,适合初学者学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

!/usr/bin/env python3.6
coding=utf-8
读文件
f = open('Test.txt') #打开文件
data = f.read() #读取文件
print(data)
# oneLine = f.readline()
# print oneLine #读取第一行
# lines = f.readlines() #把内容按行读取至一个list
# print lines
f.close() #关闭
写文件
f = open('output.txt','w') #output.txt - 文件名称及格式 w - writing
    #以这种模式打开文件,原来文件内容会被新写入的内容覆盖,如文件不存在会自动创建
f.write("I'm going to write a string")
out = open('output.txt','w')
out.write("I'm Fine \nNow is raining!")
out.close()
从控制台输入并保存
out = open('out.txt','w')
while True:
    data = input('Please Input something(Enter q quit): ')
    if data != 'q':
        out.write(data + '\n')
    else:
        break
从一个文件读取写入到另一个文件中
newFile = open('output.txt')
data = newFile.read()
out = open('out.txt','w')
out.write(data)
newFile.close()
out.close()
Eg:将文件的参数读取,并计算总和,排序
newFile = open("newFile.txt")
data = newFile.readlines()
newFile.close()
results = []

# print('所有的数据:',data) #所有的数据: ['张 23 34 45 91\n', '徐 60 77 51\n', '六 100\n', '诸葛 90 98\n']
for oneData in data:
    # print('未分割数据:',oneData) #张 23 34 45 91
    line = oneData.split() #分割字符串 #['张', '23', '34', '45', '91']
    sum = 0
    for score in line[1:]:  # 切片(取姓名后面的所有成绩)
        sum += int(score) #将所有的值相加
    res = '%s\t:%d\n' % (line[0], sum)
    results.append(res)

scoreFile = open('scoreFile.txt','w')
scoreFile.writelines(results)
scoreFile.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值