Python implements the class for reading and saving files,
This example describes how to read and save files in Python. We will share this with you for your reference. The details are as follows:
This class is written in a file named class_format.py and stored on disk D.
>>> import os>>> os.chdir("D:\\")>>> os.getcwd()'D:\\'>>> os.listdir(".")......
Put a testcsv.txt file on drive D, with the following content (there are spaces on both sides of oi ):
11003000563423 oi
The ReadData module of this Code uses csv. in this method, delimiter = '\ n' indicates that the delimiter is a line break, quotechar = "" indicates that the referenced character is a space, and quoting = csv. QUOTE_NONNUMERIC indicates that reader converts unreferenced areas to the float type, and writer references non-numeric fields with characters.
Reference: https://docs.python.org/3/library/csv.html
Usage of this module:
>>> from class_format import FormatData>>> myInstance = FormatData()>>> read_material = myInstance.ReadData("testcsv.txt")Data read!>>> read_material[1.0, 100.0, 3000.0, 56.0, 34.0, 23.0, 'oi']>>> result = myInstance.SaveData("resultcsv.txt",read_material)Data saved!
The content in testcsv.txt is written to the resultcsv.txt file.
The Code is as follows:
#!/usr/bin/python""" Chapter 15 of Beginning Programming With Python - For Dummies """import csvclass FormatData: def __init__(self, Name="",Age=0, Using_Vim=False): self.Name = Name self.Age = Age self.VimUser = Using_Vim def __str__(self): OutString = "'{0}', {1}, {2}".format(self.Name, self.Age, self.VimUser) return OutString def SaveData(self, Filename = "", DataList = []): with open(Filename, "w") as csvfile: DataWriter = csv.writer(csvfile, delimiter='\n',quotechar=" ",quoting=csv.QUOTE_NONNUMERIC) DataWriter.writerow(DataList) csvfile.close() print("Data saved!") def ReadData(self,Filename=""): with open(Filename, "r") as csvfile: DataReader = csv.reader(csvfile, delimiter='\n',quotechar=" ",quoting=csv.QUOTE_NONNUMERIC) Output = [] for Item in DataReader: Output.append(Item[0]) csvfile.close() print("Data read!") return Output