Python編寫一個文件讀寫程序(命令行程序)
def?readfromfile(filename):
with?open(filename,?'rt')?as?handle:
return?handle.read()
def?appendtofile(filename,?lines):
python怎么讀取數據?with?open(filename,?'at')?as?handle:
handle.writelines(lines)
def?itercui():
while?1:
content?=?raw_input()
if?content?in?('exit',?'quit'):
python分塊讀取文件?break
yield?content
if?__name__?==?"__main__":
filename?=?"record.log"
print?readfromfile(filename)
appendtofile(
Python如何讀取文件,filename,
[ln '\n'?for?ln?in?itercui()]
)
怎么讀取整個文件 python
Python 讀寫文本
首先需要注意的是,txt文件是具符編碼的同的txt字符編碼可同。具體是什碼,可以用 notepad 等文本編輯器查看。
python中讀取文件。讀取文件建議使用 with...as... 結構,可以自動關閉文件。
with open("text.txt", "r") as f:
text = f.read()
print(text)
如果不用 with...as... 則必須手動關閉文件:
f = open("text.txt", "r")
python讀取數據文件,text = f.read()
f.close()
print(text)
如果讀取的文件含有中文,使用內置的open可能會報錯,這個時候要用到codecs模塊:
import codecs
with codecs.open("text.txt", "r", encoding="utf-8") as f:
python讀取csv文件?text = f.read()
print(text)
(假設 text.txt 是 utf-8 編碼)
python怎么讀取txt文件
f
=
python打開文件?open("foo.txt")
#
一個對象
line
=
f.readline()
python從本地文件讀出數據,#
調文件的
readline()方法
while
line:
python讀取excel文件,line,
#
后面跟
','
將換行符
#
python讀取dat數據,print(line,
end
=
'') #
在
Python
python怎么讀取文件中的數據?3中使用
line
=
f.readline()
f.close()
python 如何將列表寫入文件
python讀取文件內容到列表、fh = open("test", 'w')
for item in item_list:
print >>fh, item
close(fh)
Python如何從文件讀取數據
1.1 讀取整個文件
python從文件中讀取內容。要讀取文件,一個包含幾行文本的文件(文件PI_DESC.txt與file_reader.py在同一目錄下)
PI_DESC.txt
3.1415926535
8979323846
2643383279
5028841971
python讀取db文件。file_reader.py
with open("PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
我們可以看出,讀取文件時,并沒有使用colse()方法,那么未妥善的關閉文件,會不會導致文件收到損壞呢?在這里是不會的,因為我們在open()方法前邊引入了關鍵字with,該關鍵字的作用是:在不需要訪問文件后將其關閉
1.2文件路徑
程序在讀取文本文件的時候,如果不給定路徑,那么它會先在當前目錄下進行檢索,有時候我們需要讀取其他文件夾中的路徑,例如:
現在文件PI_DESC.txt存儲在python目錄的子文件夾txt中
那么我們讀取文本內容的代碼得修改為:
with open("txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
給open參數傳遞的參數得給相對路徑
在Windows中,使用反斜杠(\),但是由于python中,反斜杠被視為轉義字符,在Windows最好在路徑開頭的單(雙)引號前加上r
相對路徑:即相對于程序文件的路徑
絕對路徑:即文本在硬盤上存儲的路徑
使用絕對路徑的程序怎么寫呢 ?
with open(r"D:\python\txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
1.3逐行讀取
讀取文件時,可能需要讀取文件中的每一行,要以每一行的方式來檢查文件或者修改文件,那么可以對文件對象使用for循環
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line)
程序運行結果如下:
通過運行結果我們可以看出,打印結果中間有很多空白行,這些空白行是怎么來的呢?因為在這個文件中,每行的末尾都有一個看不見的換行符,而print語句也會加一個換行符,因此每行末尾就有2個換行符:一個來自文件,另外一個來自print,消除這些換行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印結果
通過運行結果我們可以看出,打印結果中間有很多空白行,這些空白行是怎么來的呢?因為在這個文件中,每行的末尾都有一個看不見的換行符,而print語句也會加一個換行符,因此每行末尾就有2個換行符:一個來自文件,另外一個來自print,消除這些換行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印結果
1.4創建一個包含文件各行內容的列表
使用關鍵字with時,open()返回的文件對象只能在with代碼塊可用,如果要在with代碼塊外訪問文件的內容,可在with塊中將文件各行存儲在一個列表,并在with代碼塊外使用該列表
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()for line in lines:
print(line.rstrip())
1.5使用文件的內容
在上面一節中我們提到把數據提取到內存中,那么我們就可以對數據進行隨心所欲的操作了
需要:將圓周率連在一起打印出來(刪除空格),并打印其長度
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str = line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str = line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
注意最后print語句并沒有縮進,如果是縮進的話就會每取一行打印一次
打印效果如下
Python如何讀寫文本文件
1.open使用open文件后一定要記得調用文件對象的close()方比如可以用try/finally語確保最后能文件。
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。
2.讀文件讀文本文件input = open('data', 'r')
#第二個參數默認為r
input = open('data')
讀二進制文件input = open('data', 'rb')
讀取所有內容file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
讀固定字節file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
讀每行list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對象獲取每行:
for line in file_object:
process line
3.寫文件寫文本文件output = open('data.txt', 'w')
寫二進制文件output = open('data.txt', 'wb')
追加寫文件output = open('data.txt', 'a')
output .write("\n都有是好人")
output .close( )
寫數據file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
版權聲明:本站所有文章皆為原創,歡迎轉載或轉發,請保留網站地址和作者信息。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态