當前位置:首頁 » 辦公資訊 » 怎樣讀文件儲存成字典

怎樣讀文件儲存成字典

發布時間: 2022-06-11 21:12:05

Ⅰ 如何把圖片的excel轉為Python裡面的字典

如何將Excel導入Python之中呢?很簡單!做法如下:
首先我們要讀取excel要用到xlrd模塊,官網安裝先上官網安裝。
然後就可以跟著裡面的例子稍微試一下就知道怎麼用了。大概的流程是這樣的:
1、導入模塊
import xlrd
2、打開Excel文件讀取數據
data = xlrd.open_workbook('excel.xls')
3、獲取一個工作表
① table = data.sheets()[0] #通過索引順序獲取② table = data.sheet_by_index(0) #通過索引順序獲取③ table = data.sheet_by_name(u'Sheet1')#通過名稱獲取
4、獲取整行和整列的值(返回數組)
table.row_values(i)table.col_values(i)
5、獲取行數和列數
table.nrowstable.ncols
6、獲取單元格
table.cell(0,0).valuetable.cell(2,3).value
相對來說獲取cell比較有用,相當於是給了一個二維數組,剩下的想怎麼做都隨著自己性子來。這全部歸功於代碼的簡潔實用。若其中仍有若干小坑則花點時間自己琢磨下吧。以下列出的方法供人參考:
1、首先就是我的統計是根據姓名統計各個表中的信息的,但是調試發現不同的表中各個名字貌似不能夠匹配,開始懷疑過編碼問題,不過後來發現是因為 空格。因為在excel中輸入的時候很可能會順手在一些名字後面加上幾個空格或是tab鍵,這樣看起來沒什麼差別,但是程序處理的時候這就是兩個完全 不同的串了。我的解決方法是給每個獲取的字元串都加上strip()處理一下。效果良好2、還是字元串的匹配,在判斷某個單元格中的字元串(中文)是否等於我所給出的的時候發現無法匹配,並且各種unicode也不太奏效,網路過一些解決 方案,但是都比較復雜或是沒用。最後我採用了一個比較變通的方式:直接從excel中獲取我想要的值再進行比較,效果是不錯就是通用行不太好,個 呢不能問題還沒解決。
二、寫excel表
寫excel表要用到xlwt模塊,可到官網下載
下載後大致的操作流程如下:
1、導入模塊,復制代碼代碼 :
import xlwt
2、創建workbook,就是excel,這里只需要保存下,然後復制代碼:
workbook = xlwt.Workbook(encoding = 'ascii')
3、接著創建表,然後復制代碼:
worksheet = workbook.add_sheet('My Worksheet')
4、再往單元格內寫入內容,復制代碼代碼:
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
5、最後保存,復制代碼代碼如下:
workbook.save('Excel_Workbook.xls')
以上便是小編對「如何將Excel導入Python之中呢?」的大致介紹,希望能有所幫助!

Ⅱ python如何將字典寫入文件(字典中存放的是一些二維數組),再從上述文件讀數據到字典

importpickle
dictfile=open("myfile",'wb')
mydict={"a":[[1,2],[3,4]],"b":[[5,6],[7,8]]}
pickle.mp(mydict,dictfile)
dictfile.close()
dictfile=open("myfile",'rb')
readdict=pickle.load(dictfile)
print(readdict)

Ⅲ python讀取txt文件並以字典方式存儲

def load_parts(fnname): spec = {} with open(fname, 'r') as fn: #此語法在python2.5或以上可以支持 for ii in fn: i = ii.strip().split(',') if len(i) == 3: m = i[2].strip() if m.isdigit(): spec[i[0].strip()] = (i[1].strip(), int(m)) return spec

Ⅳ Python怎麼將列表,或者txt文件輸出轉化為字典啊

讀入每一行,按逗號分割,然後存到dict里就可以了。。
對於上一個問題,你把encoding設為utf-8就好了。。
我就幫你把代碼寫了吧,也算是解決了上一個問題了。。(求採納orz..)
Code
in
python
3
rate1
=
open('1.txt',
'r',
encoding='utf-8')
dic
=
dict()
for
line
in
rate1:
line
=
line.strip().split(',')
dic[line[0]]
=
line[1]
print(dic)
rate1.close()

Ⅳ python3怎麼讀取目錄下所有txt文件,並將文件名讀取順序保存到字典

import os
result = {}
for f_path,f_dir,f_files in os.walk(絕對目錄):
if not f_files:
continue
for f in f_files:
if f.spilt('.')[-1] == 'txt':
result[f] = len(result)

Ⅵ 如何使用python將指定文件里的數據讀取到字典里

route('/callback_result', methods = ["POST","GET"])
def callback_result():
try:nm = nmap.PortScanner()
instantiate nmap.PortScanner object
except nmap.PortScannerError:
sys.exit(0)
except:
sys.exit(0)

Ⅶ python 讀取txt格式文件 來填寫字典

dict_data={}
withopen('dict_2data.txt','r')asdf:
forkvin[d.strip().split('')fordindf]:
dict_data[kv[0]]=kv[1]
printdict_data

Ⅷ 如何使用python將指定文件里的數據讀取到字典

list_dict_all=[]#創建一個空列表,全局變數,用來存放字典
defAddtoDict(str_1):#定義一個函數,功能:把文件裡面的內容添加到字典中

list_str1=str_1.split(",")#讀取的行內容以字元串的形式顯示出來,使用『,』分隔字元串

line_str=[]#創建一個空列表,用來接收去掉' '的行字元串
foriinlist_str1:
x=i.strip(" ")
line_str.append(x)
#print(line_str)

dict_all={}#創建一個空字典
foriteminline_str:#遍歷列表中的行內容,列表中有3個元素
ifitem[0:3]=="url":#列表中的元素,前3個字元是否等於「url」
dict={item[0:3]:item[4:]}#dict={'url':'119.23.241.154:8080/futureloan/mvc/api/member/login'}
dict_all.update(dict)#添加dict到空字典dict_all中
#print(dict_all)
else:
dict={item.split(":")[0]:item.split(":")[1]}#除url外,取其他數據key,value到字典中
dict_all.update(dict)
list_dict_all.append(dict_all)#將字典添加到list列表中

deflist_dict(file_1):
file=open(file_1,"r+")
whileTrue:
line=file.readline()
ifline:
AddtoDict(line)
ifnotline:
break
file.close()
print(list_dict_all)

list_dict("test_date.txt")#傳入文件路徑及名稱即可實現將文件中的內容以[{},{}....]的形式輸出

test_date.txt裡面的內容

url:xx.xx.xx.xx:8080/futureloan/mvc/api/member/login,mobilephone:xxxxxxxxxxx,pwd:123456
url:xx.xx.xx.xx:8080/futureloan/mvc/api/member/login,mobilephone:xxxxxxxxxxx,pwd:123456

Ⅸ Python讀取文本內容如何變成字典

123456789101112131415def addtext(txtname,span,insert): txtfile=open(txtname); txt=txtfile.readlines() txt=['auto+'+line for line in txt] txtfile.close() txtfile=open(txtname,'w') i=0 while i+span<len(txt): txtfile.writelines(txt[i:i+span]) txtfile.write(insert) txtfile.write('\n') i+=span txtfile.writelines(txt[i:len(txt)]) txtfile.close()addtext('list.txt',2,'the laber')
每隔兩行添加一個the laber,如果希望改變間隔將代碼最後一行中間的數字2改變就行了

Ⅹ 如何從本地 讀取json文件 並用字典存儲起來

Unity 保存Json數據到本地文件(字典)
一、先導入Json 解析庫;
二、開始代碼的編寫;
[csharp] view plain

//命名空間
using System.IO;
using System.Collections.Generic;
using LitJson;
[csharp] view plain

//相關變數聲明:
private static string mFolderName;
private static string mFileName;
private static Dictionary<string, string> Dic_Value = new Dictionary<string, string>();

private static string FileName {
get {
return Path.Combine(FolderName, mFileName);
}
}

private static string FolderName {
get {
return Path.Combine(Application.persistentDataPath, mFolderName);
}
}
[csharp] view plain

//初始化方法 如有需要,可重載初始化方法
public static void Init(string pFolderName, string pFileName) {
mFolderName = pFolderName;
mFileName = pFileName;
Dic_Value.Clear();
Read();
}
[csharp] view plain

//讀取文件及json數據載入到Dictionary中
private static void Read() {
if(!Directory.Exists(FolderName)) {
Directory.CreateDirectory(FolderName);
}
if(File.Exists(FileName)) {
FileStream fs = new FileStream(FileName, FileMode.Open);
StreamReader sr = new StreamReader(fs);
JsonData values = JsonMapper.ToObject(sr.ReadToEnd());
foreach(var key in values.Keys) {
Dic_Value.Add(key, values[key].ToString());
}
if(fs != null) {
fs.Close();
}
if(sr != null) {
sr.Close();
}
}
}
[csharp] view plain

//將Dictionary數據轉成json保存到本地文件
private static void Save() {
string values = JsonMapper.ToJson(Dic_Value);
Debug.Log(values);
if(!Directory.Exists(FolderName)) {
Directory.CreateDirectory(FolderName);
}
FileStream file = new FileStream(FileName, FileMode.Create);
byte[] bts = System.Text.Encoding.UTF8.GetBytes(values);
file.Write(bts,0,bts.Length);
if(file != null) {
file.Close();
}
}
到此,簡單的保存方法基本完成了。
三、舉例使用;
拿讀寫字元串為例:
[csharp] view plain

//判斷當前是否存在該key值
public static bool HasKey(string pKey) {
return Dic_Value.ContainsKey(pKey);
}
[csharp] view plain

//讀取string值
public static string GetString(string pKey) {
if(HasKey(pKey)) {
return Dic_Value[pKey];
} else {
return string.Empty;
}
}
[csharp] view plain

//保存string值
public static void SetString(string pKey, string pValue) {
if(HasKey(pKey)) {
Dic_Value[pKey] = pValue;
} else {
Dic_Value.Add(pKey, pValue);
}
Save();
}

熱點內容
馬路上汽車的噪音在多少分貝 發布:2023-08-31 22:08:23 瀏覽:2181
應孕棒多少錢一盒 發布:2023-08-31 22:08:21 瀏覽:1648
標准養老金一年能領多少錢 發布:2023-08-31 22:05:05 瀏覽:1945
湖北通城接網線多少錢一個月 發布:2023-08-31 21:59:51 瀏覽:2014
開隨車吊車多少錢一個月 發布:2023-08-31 21:55:06 瀏覽:1774
京東付尾款怎麼知道前多少名 發布:2023-08-31 21:52:58 瀏覽:2099
在學校租鋪面一個月要多少錢 發布:2023-08-31 21:52:09 瀏覽:2238
2寸有多少厘米 發布:2023-08-31 21:50:34 瀏覽:1876
知道電壓如何算一小時多少電 發布:2023-08-31 21:46:20 瀏覽:1884
金手鐲54號圈周長是多少厘米 發布:2023-08-31 21:44:28 瀏覽:2021