Programming
Frequently used(referred) Python code
by leanu
2013. 5. 24.
개인적으로 자주 쓰거나 참조하는 Python Code 를 정리해 보았다.
File
read lines with line separator
| fpin = open(inputFile) for fline in fpin: print 'line text with newline : ', fline |
read lines without line separator
| fpin = open(inputFile) flines = fpin.splitlines() for fline in fpin: print 'line text without newline : ', fline |
File path concatenation
| outDir = 'testDir' outUserName = 'test1' outFile = 'testFile.txt' # testDir/test1/testFile.txt outFullPath = os.path.join(outDir, outUserName, outFile) |
Get Filename list
| def getFileNameList( targetDir, fileNameList ): for root, subFolders, files in os.walk(targetDir): for fileName in files: fileNameList.append(fileName) |
Create directory if it doesn’t exist
| if not os.path.exists(targetDir): os.makedirs(targetDir) |
String operations
format
| tmpStr = '%s : %d' % ('Format Test', 777) |
Fast string concatenation
| # Warning : Do not use += operator when you concatenate strings. It's very slow. result = [] for fline in flines: result.append(fline) resultStr = ''.join(result) # if you want to join string with new lines use following code # resultStr = os.linesep.join(result) |
댓글