1. window下的路径分隔符和mac上的一样吗

不一样。

Windows Mac
根文件夹 C:\ /
附加卷 D:\或E:\ /mnt
路径分隔符 \ / , 或者import os , 然后\\
2. 如何查看当前工作目录
>>> import os
>>> os.getcwd()
'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37'
3. 如何切换当前工作目录
>>> os.chdir('c:\\Program Files (x86)\\2345Soft')
>>> os.getcwd()
'c:\\Program Files (x86)\\2345Soft'
4. 如何创建新文件夹
>>> os.makedirs('C:\\Users\\DELL\\Desktop\\survey')

5. 如何将绝对路径修改为相对路径
  • os.path.abspath(path)将相对路径转换为绝对路径;

     >>> os.path.abspath('.')'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37'>>> os.path.abspath('.\\Scripts')'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\Scripts'
    
  • os.path.relpath(path,start)将绝对路径转换为相对路径;

     >>> os.path.relpath('C:\\Windows','C:\\Dell')'..\\Windows'
    
6. 如何查看一个路径的目录名称、基本名称。
  • 查看目录名称:os.path.dirname(path)

     >>> os.getcwd()'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37'>>> path='C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37'>>> os.path.dirname(path)'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python'
    
  • 查看基本名称:os.path.basename(path)

     >>> os.path.basename(path)'Python37'
    
7. os.listdir(path) 查看文件夹里面的内容
>>> os.listdir('C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37')
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
8. os.path.getsize(path) 查看一个文件大小
  • 一个程序的字节数

     >>> os.path.getsize('C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\python.exe')99856
    
  • 一个目录下所有文件的字节数

     >>> totalsize=0>>> for filename in os.listdir('C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37'):totalsize=totalsize+os.path.getsize(os.path.join('C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37',filename))>>> print(totalsize)4905545
    
9. 如何利用open读取、写入文件
  • 读入文件

     >>> hello=open('C:\\Users\\DELL\\Desktop\\hello.txt')>>> hellokkidult=hello.read()>>> hellokkidult'首页新微博\n我的收藏\n我的赞\n\n\n冷知识bot\n5分钟前\n安全出口指示牌上的绿色小人是有名字的,叫“皮特托先生”,诞生于日本。 \n\n一个App工作室\n23分钟前 来自 微博 weibo.com\n别人说你好的时候别往心里去,否则说你不好了,你也会当真。这个世界,说你好和不好的可以来自同一批人。成年人,捡对自己有用的听就好了。by @张皓宸 \n摄影 Denys Nevozhai\n\n沙雕动物在哪里\n37分钟前 来自 微博视频\n仿佛看到了亲戚家小孩子玩你的手办的样子 L沙雕动物在哪里的微博视频 \n\n思想聚焦\n53分钟前 来自 微博视频\n《红色高跟鞋》小女孩唱的超好听。 L思想聚焦的微博视频 \n\n晓書舘\n53分钟前 来自 微博 weibo.com\n你必须只有内心丰富,才能摆脱这些生活表面的相似。——王朔《致女儿书》 \n\n\n中国新闻网\n56分钟前 来自 微博 weibo.com\n【5G商用牌照将下发,你会立刻换5G手机吗?】3日,工信部称,将于近期发放5G商用牌照,这意味着用户很快就能使用上5G手机。一批5G手机也已发布,例如,华为Mate 20 X 5G版、三星 S10 5G版、小米Mix 3 5G 版、OPPO Reno 5G版、vivo NEX 5G版、中兴天机AXON 10等。不过,目前这些手机售价不菲,上万元基 ????...展开全文c\n 5G商用牌照下发后,你会立刻换5G手机吗?\n5G商用牌照下发后,你会立刻换5G手机吗?\n\n中国新闻网\n今天 07:00 来自 微博 weibo.com\n【#高考倒计时3天#!为青春,为梦想,冲刺!】#高考加油加油# 最后3天!此刻的你,可能疲惫不堪,可能迷茫困顿。但请相信,你做过的所有努力,已在冥冥中为你埋下伏笔,那些付出终会变成你人生的礼物!高考倒计时3天,愿所有的努力都不被辜负,愿拼搏的青春不留下遗憾,祝福每一位考生!\n\n锦鲤大王\n今天 06:00 来自 皮皮时光机\n【第6284只小金鱼】//@Diligent_Ping:#锦鲤还愿# @锦鲤大王 所有小愿望都实现了,档案按时顺利送到学院了,谢谢大王,下一个阶段该好好读研并为博士做准备了。\n@锦鲤大王\n【本王法力无边,关注并转我子孙锦鲤图者,一月内必有好事发生】 \n\n朱一龙工作室\n6月3日 17:29\n#朱一龙井然##我的真朋友#\n母子间的小互动,暖心井然@朱一龙 突然出现  \n\n微博客服客服热线4000-960-960意见反馈舞弊举报About Weibo开放平台微博招聘新浪网导航投诉处理大厅  \n\n京ICP证100780号互联网药品服务许可证京网文[2017]10291-1172号?京ICP备12002058号?增值电信业务经营许可证B2-20140447乙测资字1111805\n\n广播电视节目制作经营许可证(京)字第04005号Copyright  2009-2019 WEIBO 北京微梦创科网络技术有限公司京公网安备11000002000019号'
    

(这是为什么???)

>>> hello.readlines()
[]
  • 写入文件

     >>> kidultfile=open('hello.txt','w')>>> kidultfile.write('Hello world!\n')13>>> kidultfile.close()>>> kidultfile=open('hello.txt','a')>>> kidultfile.write('kidult is not vegetable.')24>>> kidultfile.close()>>> kidultfile=open('hello.txt')>>> content=kidultfile.read()>>> kidultfile.close()>>> print(content)Hello world!kidult is not vegetable.>>> os.path.abspath('.\\hello.txt')'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\hello.txt'
    
10. 利用shelve比一般的写入文件有什么优点?

shelve模块让你在程序中添加“保存”和“打开”功能。

11. 如何利用pprint写入.py后缀的文件 ?

利用pprint.pformat(变量)

>>> import os
>>> import pprint
>>> cats=[{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
>>> pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj=open('myCats.py','w')
>>> fileObj.write('cats='+pprint.pformat(cats)+'\n')
81
>>> fileObj.close()
>>> import myCats
>>> myCats.cats
[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]
>>> os.path.abspath('.\\myCats')
'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\myCats'
12. 如何复制文文件 --shutil模块

调用shutil.copy(source,destination)

>>> os.path.abspath('.\\hello')
'C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\hello'
>>> shutil.copy('C:\\Users\\DELL\\AppData\\Local\\Programs\\Python\\Python37\\hello.txt','C:\\Users\\DELL\\Desktop\\hellokidult.txt')
'C:\\Users\\DELL\\Desktop\\hellokidult.txt'
13. 如何移动文件,如何给文件改名字 --shutil模块

shutil.move(source,destination)

>>> os.makedirs('C:\\Users\\DELL\\Desktop\\hello')
>>> shutil.move('C:\\Users\\DELL\\Desktop\\hellokidult.txt','C:\\Users\\DELL\\Desktop\\hello')
'C:\\Users\\DELL\\Desktop\\hello\\hellokidult.txt'
>>> shutil.move('C:\\Users\\DELL\\Desktop\\hello.txt','C:\\Users\\DELL\\Desktop\\hello\\new_hello.txt')
'C:\\Users\\DELL\\Desktop\\hello\\new_hello.txt'

Attention:构成目的地文件夹必须已经存在。

14. 如何稳妥的删除文件(先去回收站那种)-- send2trash模块
>>> import send2trash
>>> import os
>>> helloFile=open('hello.txt','a')
>>> helloFile.close()
>>> send2trash.send2trash('hello.txt')
15. 如何压缩文件 16. 如何解压文件 (那么我偷个懒叭^^)
17. 项目实践
  • P149生成AB卷的内容,相当的漂亮!!

     #!/usr/bin/python3import randomimport pprintcapitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix','Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver','Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee','Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':'Springfield','Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':'Topeka','Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton','New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh','North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City','Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence','South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia','West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}#创建3张试卷(也可以创建更多)for i in range(3):#创建一个测验试卷文件quizFile=open('quiz%s.txt'%(i+1),'w')#创建一个试卷答案文件answerFile=open('quiz_answer%s.txt'%(i+1),'w')#给测验试卷加个头部(如让考生写姓名学号的位置,以及写分数的位置)quizFile.write('Name:\n\n Date:\n\n')quizFile.write((' '*20)+'State Capitals Quiz(Form %s)'%(i+1))quizFile.write('\n\n')#给答案文件加个头answerFile.write(' '*20+'Answer(Form %s)' % (i+1))answerFile.write('\n\n')states=list(capitals.keys()) #取出所有州#打乱random.shuffle(states)#创建答案选项for j in range(50):#correctAnswer=capitals[states[j]] #正确答案wrongAnswers=list(capitals.values())#获取所有答案列表del wrongAnswers[wrongAnswers.index(correctAnswer)]#删除正确的答案wrongAnswers=random.sample(wrongAnswers,3)#随机选取三个错误答案answersOptions=wrongAnswers+[correctAnswer]#将正确答案和错误答案连接起来random.shuffle(answersOptions)#打乱四个答案的顺序#问题quizFile.write('%s.What is the capital of %s?\n' % (j+1,states[j]))#答案for i in range(4):quizFile.write(' %s. %s\n' % ('ABCD'[i],answersOptions[i]))quizFile.write('\n')#将正确答案写入一个文件answerFile.write('%s. %s\n' % (j+1,'ABCD'[answersOptions.index(correctAnswer)]))quizFile.close()#关闭测试文件answerFile.close()#关闭答案文件
    
  • P165批量修改名字的内容,相当实用。

     #-*-coding:utf-8-*-#! python3# renameDates.py - Renames filenames with American MM-DD-YYYY date format# to European DD-MM-YYYY.import shutil,os,re# create a regex that matches files with the American date format.datePattern = re.compile(r"""^(.*?)           # all text before the date((0|1)?\d)-             # one or two digits for the month,begin with 0 or 1(optional)((0|1|2|3)?\d)-        # one or two digits for the day,begin with 0,1,2,3(optional)((19|20)\d\d)          # four digits for the year(.*?)$                  # all text after the date""",re.VERBOSE)         # 忽略正则表达式字符串中的空白符和注释# 分组表达式中分组编号每遇到一个左括号计数就加一# datePatter = re.compile(r"""^(1))#              (2(3))-#              (4(5))-#              (6(7))#              (8)$#              """,re.VERBOSE)# Loop over the files in the working firectoryfor amerFilename in os.listdir('.'):mo = datePattern.search(amerFilename)# Skip files without a date.if mo == None:continue# Get the different parts of the filename.beforePart = mo.group(1)monthPart = mo.group(2)dayPart = mo.group(4)yearPart = mo.group(6)afterPart = mo.group(8)# From the European-style filename.euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart# Get the full,absolute file paths.absWorkingDir = os.path.abspath('.')amerFilename = os.path.join(absWorkingDir,amerFilename)euroFilename = os.path.join(absWorkingDir,euroFilename)# Rename the files.print('Renaming "%s" to "%s"...'%(amerFilename,euroFilename))#shutil.move(amerFilename,euroFilename)  # uncomment after testing
    

Python学习第五弹【正则表达式】-kidult相关推荐

  1. Python学习笔记五:控制语句

    Python学习笔记五:控制语句 Pycharm 开发环境的下载安装配置_项目管理 控制语句 Pycharm 开发环境的使用 Pycharm 下载和安装 激活和选择不同UI 风格 创建项目和初始化配置 ...

  2. Python学习篇(五) Python中的循环

    文章目录 前言 一.range函数 二.while循环 2.1四步循环法 三.for in 循环 四.流程控制语句 4.1 break 4.2 continue 五.else语句 六.嵌套循环 七.二 ...

  3. 统计学习第五弹--python实践概率分布

    正态分布(Normal distribution) 正态分布(Normal distribution),又名高斯分布(Gaussian distribution),正态曲线呈钟型,两头低,中间高,左右 ...

  4. [Python学习] 专题五.列表基础知识 二维list排序、获取下标和处理txt文本实例

    通常测试人员或公司实习人员需要处理一些txt文本内容,而此时使用Python是比较方便的语言.它不光在爬取网上资料上方便,还在NLP自然语言处理方面拥有独到的优势.这篇文章主要简单的介绍使用Pytho ...

  5. Python学习笔记(五)—LOOP 循环

    个人认为Python基础学习直到LOOP才算真正开始. 循环有While, do-while, 和for() 比如while 我们要输出100条"you are my sunshine &q ...

  6. 【懒懒的Python学习笔记五】

    在这一章中,你将学习到能够将信息关联起来的Python字典,将学习如何访问和修改字典中的信息,同时也会学习如何遍历字典中的数据. 一.一个简单的字典 新建了一个存储用户信息的字典,里面存储了用户姓名. ...

  7. python学习之 re库 正则表达式

    正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配. python 通过re模块实现 re.search()方法用于在字符串中搜索正则表达式模式第一次出现的位置 搜素不存 ...

  8. python学习第五节:用面向对象实现friendbook

    课程视频链接 跟着麦叔学Python:https://b23.tv/Xx9NV0 1. 主程序 friend.py from cmd import * def print_usage():print( ...

  9. Python学习第3弹——序列、列表、元组、字典、集合

    目录 序列 索引 切片 序列相加 序列乘法 检查某个元素是否是序列的成员 计算序列的长度.最大值和最小值 计算序列的长度--len() 返回序列的最大元素--max() 返回序列的最小元素--min( ...

  10. Python学习笔记五:条件循环

    文章目录 一.再谈print和import 1. 打印多个参数 2. 导入时重命名 二.赋值魔法 1. 序列解包 2. 链式赋值 3. 增强赋值 三.代码块:缩进的乐趣 四.条件和条件语句 1. 这正 ...

最新文章

  1. 虚拟机ubuntu搭建ftp服务器配置,虚拟机VMware15 Ubuntu18.04 搭建FTP服务器
  2. 【Android应用开发】EasyDialog 源码解析
  3. 关于Configuration.ConfigurationManager
  4. cdh 安装_CDH的介绍和部署
  5. [BUUCTF-pwn]——xman_2019_format
  6. JUnit简单使用教程
  7. Cygwin 的代理设置(同 Linux)
  8. Double值保留两位小数的四种方法
  9. Office文件嵌入特殊字体
  10. 01背包和完全背包 的完整讲解版 包含 一维数组实现 和二维数组实现题目
  11. python两数相加有进退位_Python 之父透露退位隐情,与核心开发团队产生隔阂
  12. 第八届“图灵杯”NEUQ-ACM程序设计竞赛(全题解详细)
  13. opencv中step[i],step1(i),elemsize,elemsize1
  14. php 解析mpp 格式文件
  15. 24C02 EEPROM多个字节连续写入乱码问题解决
  16. mac 下安装python+selenium+firebox+pycharm+geckodriver
  17. MATLAB中广义极值分布的分析、测试、个人理解
  18. 嵌入式操作系统--篮球记分计时系统
  19. list of questions
  20. mysql int 可以是负数吗_int型包括负数吗

热门文章

  1. 下载慢怎么办?(域名遭到dns污染处理方法)
  2. Python 玩转数据 3 - NumPy ndarray Array Indexing, Slicing, Striding, View Subarray,Copy Subarray
  3. ai怎么做盒子效果图_ai怎么制作包装盒? Ai贴图工具制作包装盒的实例教程
  4. 浅谈网页压缩GZIP
  5. CS系统设计与开发——人事档案管理系统的设计与实现
  6. CPU的工作原理和内部架构
  7. c语言中switch语句流程图_C语言程序设计程序流程结构
  8. OCR文字识别【前端渲染,后端进行逻辑处理】
  9. 铁威马教程之如何轻松同步TNAS和云盘数据
  10. Java基础之==与equal()的区别