首页 > 技术文章 > python自动化之读写

dudumiaomiao 2017-05-10 19:12 原文

#############################################################################

#############在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()

推荐阅读