#Coding=utf-8#write the list to file: ' w+ ' (overwrite the original file content), ' A + ' (appended to the original file)defwrite_list_test (path,savelist,pattarn):Try: F=open (Path, Pattarn)exceptIOError:Print "the file don ' t exist, please double check!"exit ()Try: F.writelines (savelist)Print 'saved successfully!!!' finally: F.close ()#writing a string to a filedefwrite_str_test (path,savestr,pattarn):Try: F=open (Path, Pattarn)exceptIOError:Print "the file don ' t exist, please double check!"exit ()Try: F.write (SAVESTR)PrintSAVESTR,'saved successfully!!!' finally: F.close ()#detects if the file is closeddefCheck_close (fsock): S1=fsock.closedifTrue = =S1:Print 'The file is closed' Else: Print 'The file donot close' returnS1#reads files from the specified pathdefread_txt_test (path,pattarn):Try: F=open (Path, Pattarn)exceptIOError:Print "the file don ' t exist, please double check!"exit ()Try:#all_text=f.read () #读入文件的所有内容#Print All_text #Lines=f.readlines ()#For key in lines:#print Key.strip () forLineinchF:#read the contents of a file as a row PrintLine.strip ()#strip remove spaces, tab, and line breaks finally: F.close ()if __name__=='__main__':#li = ["helloword\n", "hellochina\n"]#write_list_test (' hello.txt ', Li, ' A + ')#write_str_test (' helloword.txt ', ' helloword\n ', ' A + ')#write_str_test (' helloword.txt ', ' helloword\n ', ' A + ')Read_txt_test ('Helloword.txt','R')
Python: Text file processing