Python文件处理

读取文件

本地文件

input_file = open('note.txt','r')
for line in input_file:
    line = line.strip() #去除前后空格
    print(line)
input_file.close()

若将其改为函数形式:

#filename.py
import sys

def process_file(filename):
'''Open, read, and print a file.'''    
    input_file = open(filename,'r')
    for line in input_file:
        line = line.strip()
        print(line)
    input_file.close()
if __name__ == '__main__':
    process_file(sys.argv[1])

在命令行运行该文件,输入如下命令:

python filename.py test.txt

命令中的test.txt对应于sys.argv[i]

互联网上的文件

# coding=utf-8
import urllib.request
url = 'http://www.weather.com.cn/adat/sk/101010100.html'
web_page = urllib.request.urlopen(url)
for line in web_page:
    line = line.strip()
    print(line.decode('utf-8')) #加上decode函数才能显示汉字
web_page.close()

输出结果:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"南风","WS":"2级","SD":"26%","WSE":"2","time":"10:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014"}}

若是在命令行运行该文件,输入如下命令:

python filename.py

写入文件

再打开文件时,除了需要制定文件名外,还需要制定一个模式(“r”,”w”,”a”,分别对应于读取、写入、追加)。如果没有制定模式,则应用默认模式”r”。当以写入模式打开文件且该文件尚不存在时,就会创建出一个相应的新文件。
例如,将“Computer Science”放到文件test.txt中:

output_file = open('test.txt','w')
output_file.write('Computer Science')
output_file.close()

一个同时具有读取和写入功能的事例,从输入文件的每一行读取两个数字,在另外一个文件中输出这两个数字以及它们的和。

#test.py
def mysum(input_filename, output_filename):
    input_file = open(input_filename,'r')
    output_file = open(output_filename,'w')
    for line in input_file:
        operands = line.split()
        sum_value = float(operands[0]) + float(operands[1])
        new_line = line.rstrip() + ' ' + str(sum_value) + '\n'
        output_file.write(new_line)
    output_file.close()

rstrip()函数用于去掉输入文件每行的换行符。

函数调用:

from test import *
mysum('test.txt', 'test2.txt')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值