㈠ python遍歷字元串時是逐字遍歷,遍歷txt文本時是逐行讀取,這是為什麼
for循環遍歷,實際上是返回一個迭代器,並不斷調用其next()方法的過程。next()返回什麼,取決於迭代器的具體實現,對於str類型來說,就返回下一個字元串;對於file類型來說,就返回下一行。
㈡ Python 遍歷
a=[[1,2,3,4,-1],[21,23,34,45,1],[3,4,34,2,1]]
cl_num=-1
foriinrange(len(a)-1):
this_line=a[i][cl_num]
next_line=a[i+1][cl_num]
issame=(this_line==next_line)
ifissame:
print('第{0}行第{1}列與第{2}行第{1}列相等'.format(str(i),str(cl_num),str(i+1)))
else:
print('第{0}行第{1}列與第{2}行第{1}列不相等'.format(str(i),str(cl_num),str(i+1)))
#第0行第-1列與第1行第-1列不相等
#第1行第-1列與第2行第-1列相等
此為按你要求,比較相鄰行的最後一列的值。
下次去stackoverflow上查答案或提問吧。
㈢ Python辦公,如何遍歷「資料庫導出的表格」的所有單元格,清除單元格內容的前後空字元串
由於沒有看到導出的表格樣本,直接說吧:
遍歷建議直接用pandas的itertuples(),去除前面的空白字元串用lstrip()就行
df = pd.read_excel("test.xlsx")
for row in df.itertuples():
row.行名稱=row.行名稱.lstrip()
以上應該就可以了,注意縮進。
㈣ python逐行查找關鍵字
f=open('aaa.txt')
l=f.readline()
for i in l:
if "bbb" in i:
print "OK
f.close()
打開文件aaa.txt for循環,一行一行的,如果bbb關鍵字在i這一行,列印ok
㈤ 使用Python,如何遍歷csv文件的每一行記錄的每一個欄位值
csv文件內每一行即一行數據,每一個逗號為一列數據。因此,先按行讀取一行,再按逗號分割即可。
csvfile=open('your_csv_file.csv','r')
data=[]
forlineincsvfile:
data.append(list(line.strip().split(',')))
此外,numpy.loadtxt也提供了更為便利的方法,不妨參考一下。
㈥ 怎樣用python遍歷表格中的內容
是什麼表格,是Excel當中的,還是word?如果是當中的話通過import 調入指定的關聯模塊,利用for循環或while都可以實現遍歷數據
㈦ 如何用Python os.path.walk方法遍歷搜索文件內容的操作詳解
文中使用到了Python os模塊和Python sys模塊,這兩個模塊具體的使用方法請參考玩蛇網相關文章閱讀。
Python os.path.walk方法遍歷文件搜索內容方法代碼如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os, sys
#代碼中需要用到的方法模塊導入
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb'] # ignore binary files
def visitfile(fname, searchKey):
global fcount, vcount
try:
if not listonly:
if os.path.splitext(fname)[1] in skipexts:
pass
elif open(fname).read().find(searchKey) != -1:
print'%s has %s' % (fname, searchKey)
fcount += 1
except: pass
vcount += 1
#www.iplaypy.com
def visitor(args, directoryName,filesInDirectory):
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if not os.path.isdir(fpath):
visitfile(fpath,args)
def searcher(startdir, searchkey):
global fcount, vcount
fcount = vcount = 0
os.path.walk(startdir, visitor, searchkey)
if __name__ == '__main__':
root=raw_input("type root directory:")
key=raw_input("type key:")
searcher(root,key)
print 'Found in %d files, visited %d' % (fcount, vcount)
㈧ 如何用python遍歷文件夾下的所有excel文件
大數據處理經常要用到一堆表格,然後需要把數據導入一個list中進行各種演算法分析,簡單講一下自己的做法:
1.如何讀取excel文件
網上的版本很多,在xlrd模塊基礎上,找到一些源碼:
[python]view plain
importxdrlib,sys
importxlrd
defopen_excel(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx"):
data=xlrd.open_workbook(file)
returndata
#根據索引獲取Excel表格中的數據參數:file:Excel文件路徑colnameindex:表頭列名所在行的所以,by_index:表的索引
defexcel_table_byindex(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx",colnameindex=0,by_index=0):
data=open_excel(file)
table=data.sheets()[by_index]
nrows=table.nrows#行數
ncols=table.ncols#列數
colnames=table.row_values(colnameindex)#某一行數據
list=[]
forrownuminrange(1,nrows):
row=table.row_values(rownum)
ifrow:
app={}
foriinrange(len(colnames)):
app[colnames[i]]=row[i]
list.append(app)
returnlist
#根據名稱獲取Excel表格中的數據參數:file:Excel文件路徑colnameindex:表頭列名所在行的所以,by_name:Sheet1名稱
defexcel_table_byname(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx",colnameindex=0,by_name=u'Sheet1'):
data=open_excel(file)
table=data.sheet_by_name(by_name)
nrows=table.nrows#行數
colnames=table.row_values(colnameindex)#某一行數據
list=[]
forrownuminrange(1,nrows):
row=table.row_values(rownum)
ifrow:
app={}
foriinrange(len(colnames)):
app[colnames[i]]=row[i]
list.append(app)
returnlist
defmain():
tables=excel_table_byindex()
forrowintables:
print(row)
tables=excel_table_byname()
forrowintables:
print(row)
if__name__=="__main__":
main()
- 最後一句是重點,所以這里也給代碼人點個贊!
importos
importxlrd
importtest_wy
xpath="E:/唐偉捷/電力/電力系統總文件夾/舟山電力"
xtype="xlsx"
typedata=[]
name=[]
raw_data=[]
file_path=[]
defcollect_xls(list_collect,type1):
#取得列表中所有的type文件
foreach_elementinlist_collect:
ifisinstance(each_element,list):
collect_xls(each_element,type1)
elifeach_element.endswith(type1):
typedata.insert(0,each_element)
returntypedata
#讀取所有文件夾中的xls文件
defread_xls(path,type2):
#遍歷路徑文件夾
forfileinos.walk(path):
foreach_listinfile[2]:
file_path=file[0]+"/"+each_list
#os.walk()函數返回三個參數:路徑,子文件夾,路徑下的文件,利用字元串拼接file[0]和file[2]得到文件的路徑
name.insert(0,file_path)
all_xls=collect_xls(name,type2)
#遍歷所有type文件路徑並讀取數據
forevey_nameinall_xls:
xls_data=xlrd.open_workbook(evey_name)
foreach_sheetinxls_data.sheets():
sheet_data=test_wy.excel_table_byname(evey_name,0,each_sheet.name)
#請參考讀取excel文件的代碼
raw_data.insert(0,sheet_data)
print(each_sheet.name,":Datahasbeendone.")
returnraw_data
a=read_xls(xpath,xtype)
print("Victory")
- 歡迎各種不一樣的想法~~
最後一句讓代碼里的函數都可以被復用,簡單地說:假設文件名是a,在程序中import a以後,就可以用a.excel_table_byname()和a.excel_table_byindex()這兩個超級好用的函數了。
2.然後是遍歷文件夾取得excel文件以及路徑:,原創代碼如下:
[python]view plain
㈨ python進行資料庫查詢時怎麼把結果提取出來
設置索引欄位。在開始提取數據前,先將member_id列設置為索引欄位。然後開始提取數據。
按行提取信息。第一步是按行提取數據,例如提取某個用戶的信息。
按列提取信息。第二步是按列提取數據,例如提取用戶工作年限列的所有信息。
按行與列提取信息。第三步是按行和列提取信息,把前面兩部的查詢條件放在一起,查詢特定用戶的特定信息。
在前面的基礎上繼續增加條件,增加一行同時查詢兩個特定用戶的貸款金額信息。
在前面的代碼後增加sum函數,對結果進行求和。
除了增加行的查詢條件以外,還可以增加列的查詢條件。
多個列的查詢也可以進行求和計算,在前面的代碼後增加sum函數,對這個用戶的貸款金額和年收入兩個欄位求和,並顯示出結果。
提取特定日期的信息。數據提取中還有一種很常見的需求就是按日期維度對數據進行匯總和提取,如按月,季度的匯總數據提取和按特定時間段的數據提取等等。
設置索引欄位。首先將索引欄位改為數據表中的日期欄位,這里將issue_d設置為數據表的索引欄位。按日期進行查詢和數據提取。
㈩ 如何有序遍歷mongodb python
對於mongo的操作,先安裝mongodb的python擴展,在你的命令行窗口上輸入:pipinstallpymongo,下面是例子,按需要修改_uri_auth='mongodb://user:password@localhost:27017/'#mongo有要驗證的話請自行替換user和passwordmongo_uri_no_auth='mongodb://localhost:27017/'#mongo沒有賬號密碼驗證的時候用這個database_name='request_db'#你要連接的資料庫名,自行替換你需要的庫名table_name='request_tb'#你要查詢的表名,請自行替換你需要的表名client=MongoClient(mongo_uri_no_auth)#創建了與mongodb的連接db=client[database_name]table=db[table_name]#獲取資料庫中表的游標#你要插入的數據insert_data={"name":"Mike","grade":"two","age":12,"sex":"man"}table..insert_one(insert_data)#插入一條數據#查詢數據name為Mike的記錄record=table.find_one({"name":"Mike"})printrecord