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

python讀取文本

發布時間: 2022-01-09 01:03:32

Ⅰ 用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()

Ⅱ python 讀取文本並賦值

你好,請詳細說一下你的需求,python讀取文本是很簡單的:

#-*-coding:cp936-*-
txtpath=r"a.txt"
fp=open(txtpath)
forlineinfp.readlines():
line=line.replace(" ","")
#自己根據需要設置
ifline[0:9]=="telnet_ip":
print"A",line
else:
print"B",line

fp.close()

不明白的地方請追問,採納哦!

Ⅲ 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文件

「'gbk' codec can't decode 。。。。。」是python 的編碼問題。最好你把那個txt的文件先轉換為utf8的格式,再進行讀取,而且讀取文件的那個py文件,文件的第一行加上 # -*- coding:utf-8 -*-

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

(6)python讀取文本擴展閱讀:

python控制語句

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

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

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

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

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

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

Ⅶ 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如何從文件讀取數據

1.1 讀取整個文件

要讀取文件,需要一個包含幾行文本的文件(文件PI_DESC.txt與file_reader.py在同一目錄下)

PI_DESC.txt

3.1415926535
8979323846
2643383279
5028841971

file_reader.py

with open("PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)

我們可以看出,讀取文件時,並沒有使用colse()方法,那麼未妥善的關閉文件,會不會導致文件收到損壞呢?在這里是不會的,因為我們在open()方法前邊引入了關鍵字with,該關鍵字的作用是:在不需要訪問文件後將其關閉

1.2文件路徑

程序在讀取文本文件的時候,如果不給定路徑,那麼它會先在當前目錄下進行檢索,有時候我們需要讀取其他文件夾中的路徑,例如:

Ⅸ Python:怎樣將txt文件讀取到一個字元串里

1、首先在vscode裡面添加了Python文件和用於讀取的文本文件。

Ⅹ python怎麼讀取txt文件全部數據

f=open("a.txt")
printf.read()

熱點內容
單片機android 發布:2024-09-20 09:07:24 瀏覽:759
如何提高三星a7安卓版本 發布:2024-09-20 08:42:35 瀏覽:659
如何更換伺服器網站 發布:2024-09-20 08:42:34 瀏覽:306
子彈演算法 發布:2024-09-20 08:41:55 瀏覽:284
手機版網易我的世界伺服器推薦 發布:2024-09-20 08:41:52 瀏覽:812
安卓x7怎麼邊打游戲邊看視頻 發布:2024-09-20 08:41:52 瀏覽:158
sql資料庫安全 發布:2024-09-20 08:31:32 瀏覽:89
蘋果連接id伺服器出錯是怎麼回事 發布:2024-09-20 08:01:07 瀏覽:503
編程鍵是什麼 發布:2024-09-20 07:52:47 瀏覽:653
學考密碼重置要求的證件是什麼 發布:2024-09-20 07:19:46 瀏覽:477