当前位置:网站首页>Self taught programming series - 2 file path and text reading and writing
Self taught programming series - 2 file path and text reading and writing
2022-06-26 09:08:00 【ML_ python_ get√】
File path and text reading and writing
2.1 File path
- os modular
- working space
- Different systems have different path formats
- Absolute path 、 Relative paths
- Create a new folder
- os.path
- Path conversion
- File type and size
- Does the file exist
import os
path = os.getcwd()
# Changing the work path
os.chdir('d:\\vs_code_python\\days_100\\res')
# Connection path
path1 = os.path.join(path,' Regular expressions .inynb')
# Get the path format on the computer
print(path1)
# Absolute path d:\\vs_code_python\\days_100\\res
# Relative paths ../ At the next higher level ./ At the same level
# Create folder
# os.makedirs('../exercise')
# os.path modular
# Conversion of relative path and absolute path
os.path.abspath('.')
os.path.abspath(path1)
os.path.isabs('./')
os.path.relpath('d:\\vs_code_python\\days_100\\exercise\\day_1.py',path1)
# Call the upper level \\exercise that will do
# name basename and dirname
print(os.path.basename(path1))
print(os.path.dirname(path1))
# file size
print(os.path.getsize(os.path.join(path,' Regular expressions .ipynb')))
print(os.listdir(path))
totalsize = 0
for filename in os.listdir(path):
totalsize+= os.path.getsize(os.path.join(path,filename))
print(totalsize)
# The number of characters in this folder
# Verify the effectiveness of the path
print(os.path.exists(path))
print(os.path.isdir(path))
print(os.path.isfile(os.path.join(path,' Regular expressions .ipynb')))
2.2 Read and write files
- Basic knowledge of
- text file
- Binary : Color 、excel etc.
- Read the file
- write file
# Read the file :open readlines close
fileA = open(os.path.join(path,'hello.txt'))
content = fileA.readlines()
print(content)
fileA.close()
# write file overwrite
fileB= open(os.path.join(path,'write.txt'),'w')
fileB.write('you are stupid!\n')
# And print The line feed is different , Write your own newline character when writing files
fileB.close()
# write file add to
fileC = open(os.path.join(path,'write.txt'),'a')
fileC.write('foolish\n')
fileC.write('shut up!\n')
fileC.close()
2.3 shelve modular : Commonly used
- Save the variable as shelve Class dictionary
import shelve
shelfFile = shelve.open('mycats')
cats = ['zhao','qian','sun','li']
shelfFile['cats'] = cats
shelfFile.close()
# Like a dictionary , Store all variables
shelfFile = shelve.open('mycats')
print(type(shelfFile))
print(shelfFile['cats'])
print(shelfFile.keys())
print(shelfFile.values())
print(list(shelfFile.keys()))
print(list(shelfFile.values()))
2.4 pprint modular : Simple data type
- Save the dictionary list as a module
import pprint
cats = [{
'name':'zhao',
'age':'1'},
{
'name':'qian',
'age':'2'}]
pprint.pformat(cats)
# Beautify dictionary output
fileD=open('mycats.py','w')
fileD.write('cats = ' + pprint.pformat(cats) + '\n')
fileD.close()
2.5 Project practice
- Write the test paper
- Save the state and its capital in a dictionary
- Construct according to the dictionary 50 Two questions and 35 A different answer ,35 Different papers , Each has 35 File : loop
- The sequence of questions is random , For each 50 Questions construct random answers , The right choice + Three wrong options ( Random ), And then shuffle once
- Write the questions and answers into the test paper file and generate the correct answers for each test paper
- Multiple shear plates
# Write the test paper .
import random
# Generate a dictionary
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': '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'}
# Generate test paper file and answer file
for quizNum in range(35):
quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'a')
answerFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'a')
# Write the test paper header
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum + 1))
quizFile.write('\n\n')
# Random processing of continent names
states = list(capitals.keys())
random.shuffle(states)
# Generate problems
for questionNum in range(50):
correctAnswer = capitals[states[questionNum]] # Each question generates four answers
wrongAnswers = list(capitals.values()) # Filter out the correct answers 3 individual
del wrongAnswers[wrongAnswers.index(correctAnswer)]
wrongAnswers = random.sample(wrongAnswers, 3)
answerOptions = wrongAnswers + [correctAnswer] # Get all the options and sort them randomly
random.shuffle(answerOptions)
# Write test paper file
quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1, states[questionNum]))
for i in range(4):
quizFile.write('%s. %s\n' % ('ABCD'[i], answerOptions[i]))
quizFile.write('\n')
# Write answer file
answerFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[answerOptions.index(correctAnswer)]))
quizFile.close()
answerFile.close()
# mcb.pyw Save and load text into the clipboard
# usage :py.exe mcb.pyw save argv[1] <keyword>argv[2] Save clipboard contents to a keyword
# usage :py.exe mcb.pyw <keyword>argv[1] Paste a keyword to the clipboard
# usage :py.exe mcb.pyw list argv[1] All keywords to clipboard
# sys Read the command line arguments
import sys,shelve,pyperclip
mcbshelf = shelve.open('mcb')
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
mcbshelf[sys.argv[2]] = pyperclip.paste()
elif len(sys.argv) == 2:
if sys.argv[1].lower() == 'list':
pyperclip.copy(str(list(mcbshelf.keys()))) # All keywords are pasted to the clipboard
elif sys.argv[1] in mcbshelf:
pyperclip.copy(mcbshelf[sys.argv[1]]) # If it is a keyword , Paste to clipboard
# List keywords and load content
mcbshelf.close()
The command line operations are as follows :
PS D:\vs_code_python\days_100\res> py clip.pyw save commemorate with an engraved inscription
PS D:\vs_code_python\days_100\res> py clip.pyw save Liu
PS D:\vs_code_python\days_100\res> py clip.pyw save red
PS D:\vs_code_python\days_100\res> py clip.pyw save king
PS D:\vs_code_python\days_100\res> py clip.pyw save Avenue
PS D:\vs_code_python\days_100\res> py clip.pyw list
PS D:\vs_code_python\days_100\res> py clip.pyw commemorate with an engraved inscription
PS D:\vs_code_python\days_100\res> py clip.pyw Liu
PS D:\vs_code_python\days_100\res> py clip.pyw king
Paste the results into the text :
commemorate with an engraved inscription , Imprison the way of heaven , All living beings need to go through countless disasters , Leaving the deep prison , To practice the truth commemorate with an engraved inscription , All sentient beings are also immeasurable , Jiejin ...
Little brother , I think your heaven is full . Purple light penetrates the body, which is by no means mortal ! It's a pity that if there is no one to point out . I am afraid that this baby will become hopeless
There is a kind of person , Born to fight ; Born to kill , Born to go against the sky . Wang Lin is like this
——《 Xianni 》 ear
边栏推荐
- Tutorial 1:hello behavioc
- 唯品会工作实践 : Json的deserialization应用
- Graduation thesis management system based on SSM
- 在哪个软件上开户比较安全
- ThreadLocal
- 【IVI】15.1.2 系统稳定性优化篇(LMKD Ⅱ)PSI 压力失速信息
- 关于小程序tabbar不支持传参的处理办法
- HDU - 6225 Little Boxes(__int128的使用)
- 小程序首页加载之前加载其他相关资源或配置(小程序的promise应用)
- [Matlab GUI] key ID lookup table in keyboard callback
猜你喜欢
Data warehouse (1) what is data warehouse and what are the characteristics of data warehouse
框架跳转导致定位失败的解决方法
phpcms v9去掉phpsso模块
[cloud primordial | kubernetes chapter] go deep into the foundation of all things - container (V)
Reverse crawling verification code identification login (OCR character recognition)
百度小程序富文本解析工具bdParse
Regular Expression 正则表达式
XSS cross site scripting attack
设置QCheckbox 样式的注意事项
【300+精选大厂面试题持续分享】大数据运维尖刀面试题专栏(一)
随机推荐
远程工作的一些命令
HDU - 6225 little boxes (\u int128)
编辑类型信息
MySQL cannot be found in the service (not uninstalled)
SRv6----IS-IS扩展
爬虫 对 Get/Post 请求时遇到编码问题的解决方案
行为树XML文件 热加载
框架跳转导致定位失败的解决方法
Live review | smardaten lihongfei interprets the Research Report on China's low / no code industry: the wind direction has changed
uniapp用uParse实现解析后台的富文本编辑器的内容及修改uParse样式
Fix the problem that the rich text component of the applet does not support the properties of video cover, autoplay, controls, etc
运行时端常用类的介绍
phpcms小程序插件4.0版正式上线
Chargement à chaud du fichier XML de l'arbre de comportement
Yolov5 advanced level 2 installation of labelimg
【云原生 | Kubernetes篇】深入万物基础-容器(五)
ImportError: ERROR: recursion is detected during loading of “cv2“ binary extensions. Check OpenCV in
phpcms小程序插件教程网站正式上线
报错ImportError: numpy.core.multiarray failed to import
[IVI] 15.1.2 system stability optimization (lmkd Ⅱ) psi pressure stall information