1 txt file read
Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)
The parameter file is a filename, such as ' file.txt '; mode is a pattern opened on a file, other parameters are generally not used.
Parameter explanation for function open:
The default is read-only in the open function. Other modes are:
W: Open in write mode
A: Open in Append mode
r+: Open in read-write mode
w+: Punch in read-write mode
RB: Open in binary read mode
WB: Open in binary write mode
AB: Open in binary append mode
rb+: Open in binary read/write mode
wb+: Open in binary read/write mode
ab+: Open in binary append mode
Common methods for open objects:
Read (): reads bytes into a string
ReadLine (): Open a line of the file, including line terminator
ReadLine (): Open file, read all rows
Write (): writes a string to the file and writes to the object as a string
Writelines (): Writes the list to a file, and the object is a list.
Seek (): offset
Tell (): Returns the position of the current file pointer
2 csv Read and write
Module CSV, read and write functions are required:
Read function
Reader (CSVFile, dialect= ' Excel ', **fmtparams)
Parameter description:
CSVFile, must be an object that supports iterations (Iterator), which can be a file object or a list object, or a file object that requires a "B" flag parameter when opened.
dialect, coding style, the default is the style of Excel, that is, separated by commas (,), dialect mode also supports customization, by calling the Register_dialect method to register, the following will be mentioned.
Fmtparam, a format parameter used to override the encoding style specified by the previous dialect object.
Write function
Writer (csvfile, dialect= ' Excel ', **fmtparams)
parameter meaning ibid.
3 examples
Reader = open ('Data.txt') List_data=reader.readlines () columns=List_data [0].split () List= [] forIinchList_data [1:]: List.append (I.split ()) with open ("Test.csv","WB") as Csvfile:writer=Csv.writer (csvfile)#Write Columns_name Firstwriter.writerow (columns)#write multiple lines with writerowsWriter.writerows (list)
Parsing of Write Data:
The open () function first opens the file with the name ' Test.csv ' under the current path and if the file does not exist, it is created, returning the CSVFile file object.
Csv.writer (CSVFile) Returns the writer object mywriter.
The Writerow () method is written one line at a time, and the Writerows method writes multiple rows at once.
Note: If the file ' Test.csv ' is pre-existing, calling the writer function empties the text in the original file before executing the Writerow/writerows method.
Python file format txt converted to CSV format