Read the file Three step: Import Module codecs# codecs module is mainly used for the end file garbled problem. Import codecs1, open file 2, file operation (read or write) 3, close file F = codecs.open (' 1.txt ') Text = f.read () result = Text.replace (' 1 ', ' A ') print ( Result) F.close () text.replace Replace all 1.txt inside ' 1 ' with the syntax of ' A ' codecs.open (file name, parameter two): Parameter two main: R Read W write b binary a append create a file and write the content. f = Codecs.open (2.txt, WB) f.write (' Hello world! ') F.write (' Hello python! ') Common ways to F.close () files: readlines () reads all the contents of a file, takes each line of the file as an element of a list (string) ReadLine () reads a line of content as a string next () Read the next line of content the write () must pass in the string example: F.write ("Abcd1234def") WriteLine () must pass in a sequence (list) corresponding to the ReadLines example: F.writeline ([' AAAA ', ' BBB ', [2222]]) with Codecs.open (' 1.txt ', ' RB ') as File:print (File.read ())
Python file operations