# 讀取文件
### 本地文件
~~~
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')
~~~