python循环读取文件夹里的文件(python循环读取文件)
Python使用for循环依次打开该目录下的各文件
import?os
path?=?r"F:\Python\第一周作业\task"
otherpath=r"F:\Python\其它目录"
for?filename?in?os.listdir(path):
????print(path,filename)
????fullname=os.path.join(path,filename)
????if?os.path.isfile(fullname):????????
??????????othername=os.path.join(otherpath,filename)??
??????????otherfile=open(othername,'wb')
??????????for?line?in?open(fullname,'rb'):
??????????????for?c?in?line:
??????????????????if?not?c.isdigit():otherfile.write(c)
??????????otherfile.close()
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'])
扩展资料:
python控制语句
1、if语句,当条件成立时运行语句块。经常与else, elif(相当于else if) 配合使用。
2、for语句,遍历列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素。
3、while语句,当条件为真时,循环运行语句块。
4、try语句,与except,finally配合使用处理在程序运行中出现的异常情况。
5、class语句,用于定义类型。
6、def语句,用于定义函数和类型的方法。
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文件路径
程序在读取文本文件的时候,如果不给定路径,那么它会先在当前目录下进行检索,有时候我们需要读取其他文件夹中的路径,例如:
现在文件PI_DESC.txt存储在python目录的子文件夹txt中
那么我们读取文本内容的代码得修改为:
with open("txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
给open参数传递的参数得给相对路径
在Windows中,使用反斜杠(\),但是由于python中,反斜杠被视为转义字符,在Windows最好在路径开头的单(双)引号前加上r
相对路径:即相对于程序文件的路径
绝对路径:即文本在硬盘上存储的路径
使用绝对路径的程序怎么写呢 ?
with open(r"D:\python\txt\PI_DESC.txt") as file_object:
contents = file_object.read()
print(contents)
1.3逐行读取
读取文件时,可能需要读取文件中的每一行,要以每一行的方式来检查文件或者修改文件,那么可以对文件对象使用for循环
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line)
程序运行结果如下:
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
通过运行结果我们可以看出,打印结果中间有很多空白行,这些空白行是怎么来的呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加一个换行符,因此每行末尾就有2个换行符:一个来自文件,另外一个来自print,消除这些换行符,只需要使用方法rstrip()
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
for line in file_object:
print(line.rstrip())
打印结果
1.4创建一个包含文件各行内容的列表
使用关键字with时,open()返回的文件对象只能在with代码块可用,如果要在with代码块外访问文件的内容,可在with块中将文件各行存储在一个列表,并在with代码块外使用该列表
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()for line in lines:
print(line.rstrip())
1.5使用文件的内容
在上面一节中我们提到把数据提取到内存中,那么我们就可以对数据进行随心所欲的操作了
需要:将圆周率连在一起打印出来(删除空格),并打印其长度
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
file_path = 'txt\PI_DESC.txt'with open(file_path) as file_object:
lines = file_object.readlines()pi_str = ''for line in lines:
pi_str += line.strip()print(pi_str.rstrip())print(len(pi_str.rstrip()))
注意最后print语句并没有缩进,如果是缩进的话就会每取一行打印一次
打印效果如下
python一次性读取文件夹中的所有excel文件
import pandas as pd
import os
data=pd.read_excel('/Users/kelan/Downloads/2月5日/安徽.xlsx')
a=data.columns
df_empty=pd.DataFrame(columns=a)
for parents,adds,filenames in os.walk('/Users/kelan/Downloads/2月5日'):
? ? for filename in filenames:
? ? ? ? #print(os.path.join(parents,filename))
? ? ? ? data = pd.read_excel(os.path.join(parents,filename))
? ? ? ? df_empty=df_empty.append(data,ignore_index=True)?
df_empty.to_excel('/Users/kelan/Downloads/2月5日/11.xlsx')
注意中文写入,os.walk会返回3个参数,分别是路径,目录list,文件list,取第一个和最后一个,最后一个遍历。ignore_index可以忽略索引。开始先在pandas中建一个dataframe,columns中填写行标
如何用python遍历文件夹下的所有excel文件
大数据处理经常要用到一堆表格,然后需要把数据导入一个list中进行各种算法分析,简单讲一下自己的做法:
1.如何读取excel文件
网上的版本很多,在xlrd模块基础上,找到一些源码:
[python]?view plain?copy
import??xdrlib?,sys
import?xlrd
def?open_excel(file="C:/Users/flyminer/Desktop/新建?Microsoft?Excel?工作表.xlsx"):
data?=?xlrd.open_workbook(file)
return?data
#根据索引获取Excel表格中的数据???参数:file:Excel文件路径?????colnameindex:表头列名所在行的所以??,by_index:表的索引
def?excel_table_byindex(file="C:/Users/flyminer/Desktop/新建?Microsoft?Excel?工作表.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?=[]
for?rownum?in?range(1,nrows):
row?=?table.row_values(rownum)
if?row:
app?=?{}
for?i?in?range(len(colnames)):
app[colnames[i]]?=?row[i]
list.append(app)
return?list
#根据名称获取Excel表格中的数据???参数:file:Excel文件路径?????colnameindex:表头列名所在行的所以??,by_name:Sheet1名称
def?excel_table_byname(file="C:/Users/flyminer/Desktop/新建?Microsoft?Excel?工作表.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?=[]
for?rownum?in?range(1,nrows):
row?=?table.row_values(rownum)
if?row:
app?=?{}
for?i?in?range(len(colnames)):
app[colnames[i]]?=?row[i]
list.append(app)
return?list
def?main():
tables?=?excel_table_byindex()
for?row?in?tables:
print(row)
tables?=?excel_table_byname()
for?row?in?tables:
print(row)
if?__name__=="__main__":
main()
最后一句是重点,所以这里也给代码人点个赞!
最后一句让代码里的函数都可以被复用,简单地说:假设文件名是a,在程序中import a以后,就可以用a.excel_table_byname()和a.excel_table_byindex()这两个超级好用的函数了。
2.然后是遍历文件夹取得excel文件以及路径:,原创代码如下:
[python]?view plain?copy
import?os
import?xlrd
import?test_wy
xpath="E:/唐伟捷/电力/电力系统总文件夹/舟山电力"
xtype="xlsx"
typedata?=?[]
name?=?[]
raw_data=[]
file_path=[]
def?collect_xls(list_collect,type1):
#取得列表中所有的type文件
for?each_element?in?list_collect:
if?isinstance(each_element,list):
collect_xls(each_element,type1)
elif?each_element.endswith(type1):
typedata.insert(0,each_element)
return?typedata
#读取所有文件夹中的xls文件
def?read_xls(path,type2):
#遍历路径文件夹
for?file?in?os.walk(path):
for?each_list?in?file[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文件路径并读取数据
for?evey_name?in?all_xls:
xls_data?=?xlrd.open_workbook(evey_name)
for?each_sheet?in?xls_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,":Data?has?been?done.")
return?raw_data
a=read_xls(xpath,xtype)
print("Victory")
欢迎各种不一样的想法~~
python中怎么读取文件内容
用open命令打开你要读取的文件,返回一个文件对象
然后在这个对象上执行read,readlines,readline等命令读取文件
或使用for循环自动按行读取文件