python3文本读取与写入常用代码
来源:互联网 发布:php点赞效果代码 编辑:程序博客网 时间:2024/04/29 12:10
创建文件夹:import osimport shutildef buildfile(echkeyfile):if os.path.exists(echkeyfile): #创建前先判断是否存在文件夹,if存在则删除 shutil.rmtree(echkeyfile) os.makedirs(echkeyfile) else: os.makedirs(echkeyfile)#else则创建语句return echkeyfile#返回创建路径#传入的参数是需要创建文件夹的路径,比如我想在D盘下创建一个名字为newfile的文件夹,则传入参数为r’ D:\newfile’。同样,返回的参数也是r’ D:\newfile’写入文本1:import codecsdef write_txt(txt, path): f = codecs.open(path, 'a', 'utf8') f.write(str(txt)) f.close()# 传入参数为txt,path;txt为需要写入的内容,数据类型为字符串,path为写入的内容,数据类型为字符串。# 传入的path需如下定义:path= r’ D:\text.txt’# f = codecs.open(path, 'a', 'utf8')中,codecs为包,需要用impor引入,’a’表示追加写入txt,可以换成’w’,表示覆盖写入。'utf8'表述写入的编码,可以换成'utf16'等。写入文本2(等同于写入文本1,但是这个比较常用):import codecsdef writetxt(path, content, code): with codecs.open(path, 'a', encoding=code)as f: f.write(content) return path+' is ok!'读取txt:def read_txt(path): with open(path, 'r', encoding='utf8') as f: lines = f.readlines() return lines# 表示按行读取txt文件,utf8表示读取编码为utf8的文件,可以根据需求改成utf16,或者GBK等。# 返回的为数组,每一个数组的元素代表一行,若想返回字符串格式,可以将改写成return ‘\n’.join(lines) 读取Excel文件:import xlrddef read_xls(path): xl = xlrd.open_workbook(path) sheet = xl.sheets()[0] # 0表示读取第一个工作表sheet data = [] for i in range(0, sheet.ncols): # ncols表示按列读取 data.append(list(sheet.col_values(i))) return data# xlrd为第三方包,可以通过用pip下载,具体操作:打开运行,输入cmd→在cmd中输入pip install xlrd,enter →等待安装完成即可。在后续若存在需要使用的第三方包,都可以通过这种方式下载和安装。# 传入参数为path,path为excel所在路径。# 传入的path需如下定义:path= r’ D:\excel.xlsx’或path= r’ D:\excel.xls’# col_values(i)表示按照一列中的所有单元格遍历读取# 可以根据需求,把col替换成row,则表示按行读取# return data :返回的data是一个二维数组,根据col和row,传回的数据呈现形式也不同,即row是col的转置。 遍历文件夹:def file_walker(path): fileArray = [] for root, dirs, files in os.walk(path): for fn in files: eachpath = str(root+'\\'+fn) fileArray.append(eachpath) return fileArray# 传入参数为path,path为需要遍历的文件夹路径。# return fileArray 返回的是当前文件下所有文件的绝对路径
9 0
- python3文本读取与写入常用代码
- 常用的testbench和matlab代码之读取和写入文本代码
- PHP大数据文本读取与写入
- 简单文本的读取与写入
- python3 读取写入Excel
- 文本写入读取
- java文本读取写入
- 【C#】对文本、图片、音频文件的读取与写入
- java逐行写入读取文本
- .net读取写入文本操作
- Perl读取文本格式化后写入文本
- python3将csv文件中的两列数据读取出来,并且按行写入txt文本之中
- delphi 写入文本教程代码
- VC++ 写入TXT文本代码
- C#写入TXT文本代码
- 简单的文本写入代码
- 写入与读取
- KissXML 读取与写入
- Port 8080 required by Tomcat v7.0 Server at localhost is already in use. The server may already be
- Game machine
- 设置全局NPM
- bzoj1188: [HNOI2007]分裂游戏
- nginx: [emerg] invalid number of arguments in "user" directive in /usr/local/nginx/conf/nginx.conf:5
- python3文本读取与写入常用代码
- BP神经网络 -- 详细教程
- 欧几里得算法
- Android App 性能优化方案
- MG loves gold (map)
- Java使用占位符拼接字符串
- [LintCode]Maximum Average Subarray
- nyoj 17 单调递增最长子序列(dp---记忆化搜索||穷举|| nlogn算法)
- 指向常量对象的指针 和 常量指针 区别