當前位置:首頁 » 編程語言 » python讀取文件

python讀取文件

發布時間: 2022-01-09 04:44:02

python 讀取文件,怎麼打開

  1. 我們需要新建一個文本文檔,這個文檔可以是windox自帶的記事本;

⑵ 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( )

⑶ python怎麼讀取txt文件

方法一:


f=open("foo.txt")#返回一個文件對象
line=f.readline()#調用文件的readline()方法
whileline:
printline,#後面跟','將忽略換行符
#print(line,end='')#在Python3中使用
line=f.readline()

f.close()

方法二:
for line in open("foo.txt"):
print line,

方法三:

f=open("c:\1.txt","r")

lines=f.readlines()#讀取全部內容

forlineinlines

printline

黑馬程序員的Python課程非常的全面系統,網上也有很多的免費教程,想學習的小夥伴,可以下載學習下。

⑷ Python 如何優雅地讀取TXT文件的內容

defloadData(path):
data=list()
withopen(path,'r')asfileReader:
lines=fileReader.readlines()#讀取全部內容
forlineinlines:
line=line.strip()
line=line.split(" ")#根據數據間的分隔符切割行數據
data.append(line[:])

data=np.array(data)
data=data.astype(float)
np.random.shuffle(data)
label=data[:,0]
features=data[:,1:]
print("dataloaded!")
returnfeatures,label-1

⑸ python怎麼讀取文件夾內容

#encoding:utf-8
importos

#設置文件夾所在路徑,我這里設置哦當前路徑
path='./'
#列出路徑下所有的一級目錄+文件
files=os.listdir(path)
printfiles

#利用遞歸,列出目錄下包括子目錄所有的文件及文件夾(但是沒有分級,如果需要分級,自己寫吧)
files1=[]
deflistfiles(path):
foriinos.listdir(path):
ifos.path.isdir(path+i):
files1.append(i)
listfiles(path+i)
else:
files1.append(i)
listfiles(path)
printfiles1

⑹ 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)

⑺ 如何讀取python的.py文件

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

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

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

cdC:Usersqc
python
>>>importex25

如果從其它地方進入python:

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

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

⑻ 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'])

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

python控制語句

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

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

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

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

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

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

熱點內容
安卓手機如何登陸刺激戰場國際服 發布:2024-05-20 01:29:02 瀏覽:860
伺服器核庫怎麼找 發布:2024-05-20 01:28:14 瀏覽:374
鹽存儲水分 發布:2024-05-20 01:09:03 瀏覽:809
中國移動用什麼服務密碼 發布:2024-05-20 00:52:10 瀏覽:695
make編譯輸出 發布:2024-05-20 00:37:01 瀏覽:67
4200存儲伺服器 發布:2024-05-20 00:20:35 瀏覽:160
解壓小生活 發布:2024-05-20 00:15:03 瀏覽:143
粘土小游戲伺服器ip 發布:2024-05-20 00:14:00 瀏覽:196
魔獸世界如何快速增加伺服器 發布:2024-05-19 23:53:37 瀏覽:694
安卓手機如何轉入蘋果手機內 發布:2024-05-19 23:50:35 瀏覽:405