導航:首頁 > 編程語言 > python讀取文件

python讀取文件

發布時間:2022-02-25 17:51:53

A. 怎麼讀取整個文件 python

Python 讀寫文本文件

首先需要注意的是,txt文件是具有字元編碼的,不同的txt字元編碼可能不同。具體是什麼編碼,可以用 notepad++ 等文本編輯器查看。
讀取文件建議使用 with...as... 結構,可以自動關閉文件。

with open("text.txt", "r") as f:
text = f.read()
print(text)

如果不用 with...as... 則必須手動關閉文件:

f = open("text.txt", "r")
text = f.read()
f.close()
print(text)

如果讀取的文件含有中文,使用內置的open可能會報錯,這個時候要用到codecs模塊:

import codecs
with codecs.open("text.txt", "r", encoding="utf-8") as f:
text = f.read()
print(text)

(假設 text.txt 是 utf-8 編碼)

B. 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( )

C. Python讀取文件內容的方法有幾種

filename=open('i:\\install\\test.txt','r+')#讀取xx路徑xx文件;r+代表的是讀寫並存方式 print filename.read()#讀取所有的文件

D. 用python讀取文本文件,對讀出的每一行進行操作,這個怎麼寫

用python讀取文本文件,對讀出的每一行進行操作,寫法如下:

f=open("test.txt","r")

whileTrue:

line=f.readline()

ifline:

pass#dosomethinghere

line=line.strip()

p=line.rfind('.')

filename=line[0:p]

print"create%s"%line

else:

break

f.close()

E. python讀取文件內容

fname = raw_input('input filename:')

with open(fname,'r') as f:
for i in f:
print i

這樣試試呢?
你的代碼本身看是沒問題的呢!

F. python 怎麼完整的讀取文件

file=open("a.txt")
s=file.read()
print(s)

G. python 讀取文件

#!/usr/bin/python2.7
import random,re
f0=file('proxys.txt','r')
dat0=f0.readlines()
f0.close()
#提取含有$1sec的行(我理解你想按sec的大小排序。)
dat1=[]
for i in dat0:
dat1.append((i,re.search(r'\$(\d+)sec',i).group(1)))
#現在dat1裡面的數據是在原來的每一行前面加了一列sec的值。
dat2=[]
for i in dat1:
if i[0]==1:
dat2.append(i[1])
#現在取出了所有sec==1的行,隨機取一行
dat3=random.choice(dat2)
c1=re.search(r'((\d{1,3}\.?){4}):(\d+)',dat3).group(1)
c2=re.search(r'((\d{1,3}\.?){4}):(\d+)',dat3).group(3)

H. 如何讀取python的.py文件

你說的環境變數其實是系統的環境變數,

進入python後,還要配置python自己的環境變數。

首先,你應該進入C:Usersqc後,再啟動python

cdC:Usersqc
python
>>>importex25

如果從其它地方進入python:

CMD進入python後,要加入路徑:

>>>importsys
>>>sys.path.insert(0,"C:\Users\qc")
>>>importex25

I. python如何讀取文件的內容

# _*_ coding: utf-8 _*_

import pandas as pd

# 獲取文件的內容

def get_contends(path):

with open(path) as file_object:

contends = file_object.read()

return contends

# 將一行內容變成數組

def get_contends_arr(contends):

contends_arr_new = []

contends_arr = str(contends).split(']')

for i in range(len(contends_arr)):

if (contends_arr[i].__contains__('[')):

index = contends_arr[i].rfind('[')

temp_str = contends_arr[i][index + 1:]

if temp_str.__contains__('"'):

contends_arr_new.append(temp_str.replace('"', ''))

# print(index)

# print(contends_arr[i])

return contends_arr_new

if __name__ == '__main__':

path = 'event.txt'

contends = get_contends(path)

contends_arr = get_contends_arr(contends)

contents = []

for content in contends_arr:

contents.append(content.split(','))

df = pd.DataFrame(contents, columns=['shelf_code', 'robotid', 'event', 'time'])

(9)python讀取文件擴展閱讀:

python控制語句

1、if語句,當條件成立時運行語句塊。經常與else, elif(相當於else if) 配合使用。

2、for語句,遍歷列表、字元串、字典、集合等迭代器,依次處理迭代器中的每個元素。

3、while語句,當條件為真時,循環運行語句塊。

4、try語句,與except,finally配合使用處理在程序運行中出現的異常情況。

5、class語句,用於定義類型。

6、def語句,用於定義函數和類型的方法。

J. python讀取文件

閱讀全文

與python讀取文件相關的資料

熱點內容
優信二手車解壓後過戶 瀏覽:63
Windows常用c編譯器 瀏覽:780
關於改善國家網路安全的行政命令 瀏覽:835
安卓如何下載網易荒野pc服 瀏覽:656
javainetaddress 瀏覽:106
蘋果4s固件下載完了怎麼解壓 瀏覽:1005
命令zpa 瀏覽:288
python編譯器小程序 瀏覽:946
在app上看視頻怎麼光線調暗 瀏覽:542
可以中文解壓的解壓軟體 瀏覽:595
安卓卸載組件應用怎麼安裝 瀏覽:915
使用面向對象編程的方式 瀏覽:342
程序員項目經理的年終總結範文 瀏覽:932
內衣的加密設計用來幹嘛的 瀏覽:435
淮安數據加密 瀏覽:295
魔高一丈指標源碼 瀏覽:984
松下php研究所 瀏覽:171
c回調java 瀏覽:403
夢幻端游長安地圖互通源碼 瀏覽:747
電腦本地文件如何上傳伺服器 瀏覽:315