当前位置:网站首页>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
边栏推荐
- Fix the problem that the rich text component of the applet does not support the properties of video cover, autoplay, controls, etc
- phpcms小程序接口新增万能接口get_diy.php
- 20220623 getting started with Adobe Illustrator
- Tutorial 1:hello behavioc
- 浅谈一下Type-C接口发展历程
- [QNX Hypervisor 2.2用户手册]12.2 术语(二)
- Yolov5进阶之五GPU环境搭建
- Which software is safer to open an account on
- 1.Intro_ Math (white board derivation and reprint of station B)
- 力扣399【除法求值】【并查集】
猜你喜欢

20220623 getting started with Adobe Illustrator

【C】青蛙跳台阶和汉诺塔问题(递归)

phpcms v9手机访问电脑站一对一跳转对应手机站页面插件

phpcms小程序插件4.0版正式上线

爬虫 对 Get/Post 请求时遇到编码问题的解决方案

PD快充磁吸移动电源方案

Fast construction of neural network

深度学习论文阅读目标检测篇(七)中文版:YOLOv4《Optimal Speed and Accuracy of Object Detection》

Yolov5进阶之三训练环境

Solution to the encoding problem encountered by the crawler when requesting get/post
随机推荐
How to convert wechat applet into Baidu applet
Machine learning (Part 2)
Phpcms V9 adds the reading amount field in the background, and the reading amount can be modified at will
phpcms v9商城模块(修复自带支付宝接口bug)
docker安装redis
【MATLAB GUI】 键盘回调中按键识别符查找表
[QNX Hypervisor 2.2用户手册]12.2 术语(二)
Data warehouse (1) what is data warehouse and what are the characteristics of data warehouse
隐藏式列表菜单以及窗口转换在Selenium 中的应用
Implementation code of interceptor and filter
Phpcms V9 background article list adds one click push to Baidu function
【微积分】拉格朗日乘子法
运行时端常用类的介绍
ThreadLocal
行为树 文件说明
Live review | smardaten lihongfei interprets the Research Report on China's low / no code industry: the wind direction has changed
Yolov5 advanced zero environment rapid creation and testing
Fast construction of neural network
Which software is safer to open an account on
Sublime Text3 common plug-ins