当前位置:网站首页>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√

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 

原网站

版权声明
本文为[ML_ python_ get√]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170553131866.html