This article describes how to use Python to traverse folders and read and write files. For more information, see
Analysis on demand
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.
Implementation process
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)
Work-ready
I recently tried several common Python IDEs and found that Subline tx2 has poor support for Chinese, 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;
For more articles about Python's implementation of folder traversal and file reading and writing, please follow the PHP Chinese network!