Python: Text file processing

Source: Internet
Author: User

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.