Python traverses folders and reads and writes files,
1. Read all files in the specified directory
2. Read the specified file and output the File Content
3. Create a file and save it to the specified directory.
Python code writing is concise and efficient, and only about 40 lines of code are used for the above functions ~ Yesterday I wrote nearly 60 lines of code to write, create, copy, and rename a file in Java;
However, the cost of simplicity is to sacrifice a little bit of running speed, but with the improvement of hardware performance, the running speed difference will become smaller and smaller until humans cannot notice ~
#-*-Coding: UTF-8-*-''' 1. Read all files in the specified directory. 2. Read the specified file, output file content 3. Create a file and save it to the specified directory '''import OS # traverse the specified directory to display all file names in the directory def eachFile (filepath): pathDir = OS. listdir (filepath) for allDir in pathDir: child = OS. path. join ('% s % s' % (filepath, allDir) print child. decode ('gbk ')#. decode ('gbk') solves the problem of garbled characters in Chinese display # Read the file content and print def readFile (filename): fopen = open (filename, 'R ') # r indicates read for eachLine in fopen: print "The read content is as follows:", ea ChLine fopen. close () # enter multiple lines of text, write the specified file, and save it to the specified folder def writeFile (filename): fopen = open (filename, 'w ') print "\ r please input multiple lines of text", "(input. press enter to save) "while True: aLine = raw_input () if aLine! = ".": Fopen. write ('% s % s' % (aLine, OS. linesep) else: print "file saved! "Break fopen. close () if _ name _ = '_ main _': filePath = "D: \ FileDemo \ Java \ myJava.txt" filePathI = "D: \ FileDemo \ Python \ pt. py "filePathC =" C: \ "eachFile (filePathC) readFile (filePath) writeFile (filePathI)
I recently tried several common Python IDES and found that the Subline tx2 IDE does not support Chinese well, and it is inconvenient to customize the color of NotePad ++ code.
It is the best way to use Eclipse. After installing the PyDev plug-in, it is very convenient to compile Python code;