Scenario: The file name contains the school number and user name, where the user name in the former learning in the after, the number is 2, such as harry33.txt, Natasha12.txt.
Requirements: separate and save the username and the number from the excle in multiple file Names.
Code section:
Import os# Create a beacon that holds the filename after the extension is removed=[]# os.walk: traverse all files and folders in a directory forA,b,filesinchOs.walk ('Test'): # If the file exists, save the start to the fourth-lowest character to the filename listiffiles: # extension 3 letters+the previous point (.), which is a total of 4 characters, is truncated to the fourth character and gets the filename filename.append ([file[:-4] forFileinchFiles]) #print (os.listdir ('Test') ) View full file contents #print (filename) View remove extension to content # create an Excel table name to save the file name fname='Testexam'# Table Counter i=0# loop filename to read a different file name forFilesinchfilename: # Generate an Excel table file with a suffix f= Open (fname+str (i) +'. xls','W'# writes the read file name to the newly generated Excel file forNameinchfiles : #文件名倒数两位是数字号码, extracted separately and placed in front of excel; the file starts to the bottom 2nd is the name information, extracted and placed behind F.write (name[-2:]+'\ t'+name[:-2]+'\ n') F.close () i+=1Print ('Build succeeded! ')
Execution Result:
Python tools-read specific information from a file name to an Excel table