Python文件处理
最后更新于:2022-04-01 16:06:08
# 读取文件
### 本地文件
~~~
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')
~~~