python自动化之读写
#############################################################################
#############在Windows上:路径使用倒斜杠作为文件夹之间的分隔符###############
#############在OS X和Linux上:使用正斜杠作为文件夹之间的分隔符###############
import os
os.path.join('usr','bin','spam') ########根据不同系统得到不同路径#########
myFiles=['accounts.txt','detailes.csv','invite.docx']
for filename in myFiles:
print(os.path.join('C:\\Users\\asweigart',filename))
##############################当前工作目录###################################
os.getcwd()
##############################改变工作目录###################################
os.chdir('C:\\Windows\\System32')
#############################创建新文件夹####################################
os.makedirs('C:\\delicious\\walnut\\waffles') ####将创建所有必要的中间文件夹
####################处理绝对路径和相对路径###################################
os.path.abspath('.') ####返回当前路径下的绝对路径
os.path.isabs(path) ####如果参数是一个绝对路径,就返回True,如果参数是一个
####相对路径,就返回False
os.path.relpath(path,start) ####将返回从start路径到path的相对路径的字符串
path='C:\\Windows\\System32\\calc.exe'
os.path.basename(path) ####文件名
os.path.dirname(path) ####对应整个文件夹名
calcFilePath='C:\\Windows\\System32\\calc.exe'
os.path.split(calcFilePath) ####得出文件名+对应整个文件夹名
os.path.getsize('C:\\Windows\\System32\\calc.exe')
##########调用os.path.getsize(path) 将返回path参数中文件的字节数
os.listdir('C:\\Windows\\System32')
##########调用os.listdir(path) 将返回文件名字符串的列表
##########该目录下所有文件的总字节数
totalsize=0
for filename in os.listdir('C:\\Windows\\System32'):
totalsize=totalsize+os.path.getsize(os.path.join('C:\\Windows\\System32'+filename))
print(totalsize)
##########检查路径有效性
os.path.exists('C:\\Windows') ####所指的文件或文件夹是否存在
os.path.isdir('C:\\Windows\\System32') ####所指的文件夹是否存在
os.path.isfile('C:\\Windows\\System32') ####所指的文件是否存在
#########文件读写过程
helloFile=open('C:\\Users\\your_home_folder\\hello.txt') ####调用open()将返回一个File对象,保存到helloFile中
helloContent=helloFile.read() ####File对象的read()方法,将整个文件的内容读取为一个字符串值
helloFile.readlines() #####从该文件取得一个字符串的列表,列表中的每个字符串是文件中的每一行
########写入文件
#####写模式:从头开始,将'w'作为第二个参数传递给open()
#####写模式:添加,将'a'作为第二个参数传递给open()
#####打开后需要File.close()
#####write()方法不同于print()(能自动添加换行符),需要手动添加
##########################漂亮打印:将列表或字典中的内容"漂亮打印"到屏幕上
import pprint
message='It was a braight cold day in April, and the clocks were striking thirteen.'
count={}
for character in message:
count.setdefault(character,0)
count[character]=count[character]+1
pprint.pprint(count)
###########pprint.pformat()将返回同样的文本字符串,不仅易于阅读,同时也是语法上正确的python代码
import pprint
cats=[{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)
fileObj=open('mycats.py','w')
fileObj.write('cats='+pprint.pformat(cats)+'\n')
fileObj.close()
#####用shelve模块保存变量
import shelve
shelfFile=shelve.open('mydata')
cats=['Zophie','Pooka','Simon']
shelfFile['cats']=cats
shelfFile.close()
####就像字典一样,shelf值有keys()和values()方法,返回shelf中键和值的类似列表的值
shelfFile=shelve.open('mydata')
list(shelfFile.keys())
list(shelfFile.valus())
shelfFile.close()
############疯狂填词
import os
import re
lib=open(r'C:\Python27\Lib\site-packages\xy\libs.txt')
libstr=lib.read()
sillyregex=re.compile(r'ADJECTIVE')
libstr=sillyregex.sub('silly',libstr)
chandelierregex=re.compile(r'NOUN')
libstr=chandelierregex.sub('chandelier',libstr)
print libstr
fileObj=open(r'C:\Python27\Lib\site-packages\xy\file.txt','w')
fileObj.write(libstr)
fileObj.close()
####
######################################################################################################
# -*- coding: utf-8 -*-
"""
Created on Thu May 04 11:12:41 2017
@author: Sl
"""
"""
##########################################################需制作###################################################################
#1、35份不同的测试试卷
#2、每份试卷创建25个多重选择题,次序随机
#3、每个问题提供一个正确答案和3个随机的错误答案,次序随机
#4、将测试试卷写到35个文本中
#5、将答案写到35个文本中
###################################################################################################################################
"""
import random
capitals={'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':'Topela','Kentucky':'Frankfort',
'Louisiana':'Baton Rouge','Maine':'Augusta','Maryland':'Annapolis','Massachusetts':'Boston','Michigan':'Lansing','Minnesota':'Saint Paul',
'Mississippi':'Jackson','Missouri':'Jefferson City'}
for quizNum in range(35):
quizFile=open(r'C:\Python27\Lib\site-packages\xy\capitals\capitalsquiz%s'%(quizNum+1),'w')
answerFile=open(r'C:\Python27\Lib\site-packages\xy\capitals\capitalsquiz_answer%s'%(quizNum+1),'w')
quizFile.write('Name:\n\nDate:\n\nperiod:\n\n')
quizFile.write(' '*20+'State Capitals Quiz (Form %s)'%(quizNum+1))
quizFile.write('\n\n')
states=list(capitals.keys())
random.shuffle(states)
for questonNum in range(25):
correctAnswer=capitals[states[questonNum]]
wrongAnswer=list(capitals.values())
del wrongAnswer[wrongAnswer.index(correctAnswer)]
wrongAnswer=random.sample(wrongAnswer,3)
answerOptions=wrongAnswer+[correctAnswer]
random.shuffle(answerOptions)
quizFile.write('%s. What is the capitals of %s?\n'% (questonNum+1,states[questonNum]))
quizFile.write('\n')
for i in range(4):
quizFile.write('%s. %s\n'%('ABCD'[i],answerOptions[i]))
quizFile.write('\n')
answerFile.write('%s. %s\n'%(questonNum+1,'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerFile.close()
######################################################################################################
'''
@pyw.exe C:\\Python34\mcb.pyw %*
##########多重剪贴板
#注释和shelf设置
'''
import shelve,pyperclip,sys
mcbshelf=shelve.open('mcb')
#TODO:save clipboard content
if len(sys.argv)==3 and sys.argv[1].lower()=='save':
mcbshelf[sys.argv[2]]==pyperclip.paste()
elif len(sys.argv)==2:
#TODO:List Keywords and load content
if sys.argv[1].lower()=='list':
pyperclip.copy(str(list(mcbshelf.keys())))
elif sys.argv[1] in mcbshelf:
pyperclip.copy(mcbshelf[sys.argv[1]])
mcbshelf.close()
python自动化之读写的更多相关文章
- python自动化运维学习第一天--day1
学习python自动化运维第一天自己总结的作业 所使用到知识:json模块,用于数据转化sys.exit 用于中断循环退出程序字符串格式化.format字典.文件打开读写with open(file, ...
- python自动化开发学习 I/O多路复用
python自动化开发学习 I/O多路复用 一. 简介 socketserver在内部是由I/O多路复用,多线程和多进程,实现了并发通信.IO多路复用的系统消耗很小. IO多路复用底层就是监听so ...
- Python自动化办公知识点整理汇总
知乎上有人提问:用python进行办公自动化都需要学习什么知识呢? 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很多已经做案例的人,却 ...
- flow.ci + Github + Slack 一步步搭建 Python 自动化持续集成
理想的程序员必须懒惰,永远追随自动化法则.Automating shapes smarter future. 在一个 Python 项目的开发过程中可能会做的事情:编译.手动或自动化测试.部署环境配置 ...
- Selenium2+python自动化23-富文本(自动发帖)
前言 富文本编辑框是做web自动化最常见的场景,有很多小伙伴遇到了不知道无从下手,本篇以博客园的编辑器为例,解决如何定位富文本,输入文本内容 一.加载配置 1.打开博客园写随笔,首先需要登录,这里为了 ...
- Selenium2+python自动化24-js处理富文本(带iframe)
前言 上一篇Selenium2+python自动化23-富文本(自动发帖)解决了富文本上iframe问题,其实没什么特别之处,主要是iframe的切换,本篇讲解通过js的方法处理富文本上iframe的 ...
- Selenium2+python自动化7-xpath定位
前言 在上一篇简单的介绍了用工具查看目标元素的xpath地址,工具查看比较死板,不够灵活,有时候直接复制粘贴会定位不到.这个时候就需要自己手动的去写xpath了,这一篇详细讲解xpath的一些语法. ...
- Selenium2+python自动化13-Alert
不是所有的弹出框都叫alert,在使用alert方法前,先要识别出它到底是不是alert.先认清楚alert长什么样子,下次碰到了,就可以用对应方法解决.alert\confirm\prompt弹出框 ...
- 【python自动化第十一篇】
[python自动化第十一篇:] 课程简介 gevent协程 select/poll/epoll/异步IO/事件驱动 RabbitMQ队列 上节课回顾 进程: 进程的诞生时为了处理多任务,资源的隔离, ...
随机推荐
- Html.RenderPartial与Html.RenderAction的区别
Html.RenderPartial与Html.RenderAction这两个方法都是用来在界面上嵌入用户控件的. Html.RenderPartial是直接将用户控件嵌入到界面上: <%Htm ...
- 一步步实现一个基本的缓存模块·续, 添加Memcached调用实现
jusfr 原创,转载请注明来自博客园. 在之前的实现中,我们初步实现了一个缓存模块:包含一个基于Http请求的缓存实现,一个基于HttpRuntime.Cache进程级的缓存实现,但观察代码,会发现 ...
- linux设置禁止ping
linux禁止ping为了服务器的安全, 防止网络攻击(DOS 攻击消耗网络宽带,CPU资源), 需要服务器设置 禁止ping通常有两种方式第一种是通过防火墙 iptables 设置第二种是内核设置 ...
- python数据分析的工具环境
python做数据分析的优势: 拥有大量的库为数据分析和处理提供了完整的工具链 随着库还在不断的增加的同时, 算法的实现也更加的创新.Numpy, matplotlib, scipy,scikit-l ...
- AssetBundle一些问题
AssetBundle划分过细的问题,比如每个资源都是AssetBundle. 加载IO次数过多,从而增大了硬件设备耗能和发热的压力: Unity 5.3 ~ 5.5 版本中,Android平台上在不 ...
- python基础学习笔记(一)
最好有点c++基础来看,,每天都更新一篇吧 这一篇是一些基础东西 1.运算符2.变量3.基本输入输出4.字符串5.列表6.元组7.字典8.集合9.简单的说下循环啥的 1.运算符 特别的 a / b:为 ...
- 报错android.view.InflateException: Binary XML file line #11: Attempt to invoke virtual method 'boolean
出现这种问题,打开Android monitor的调试信息发现是 android.view.InflateException: Binary XML file line #11: Attempt to ...
- 【坚持】Selenium+Python学习记录 DAY10
2018/05/31-2018/06/1 [官方文档](https://www.jetbrains.com/help/pycharm/set-up-a-git-repository.html) 通过p ...
- 剑指 Offer——连续子数组的最大和
1. 题目 2. 解答 初始化 sum=0,然后遍历数组进行累加.如果 sum 变为负数,也就说再继续累加的话贡献为负,我们需要更新 sum=0,重新开始累加. 初始化 max_sum 为数组的第一个 ...
- 【推荐系统】neural_collaborative_filtering(源码解析)
很久没看推荐系统相关的论文了,最近发现一篇2017年的论文,感觉不错. 原始论文 https://arxiv.org/pdf/1708.05031.pdf 网上有翻译了 https://www.cnb ...