Python implements a class that reads and saves files

  • 2020-06-01 10:08:17
  • OfStack

This article demonstrates an example of a class that implements Python to read and save files. I will share it with you for your reference as follows:

This class is written in a file called on the D disk

>>> import os
>>> os.chdir("D:\\")
>>> os.getcwd()
>>> os.listdir(".")

There is one testcsv.txt file on the D disk, which reads as follows (oi has Spaces on both sides) :


The ReadData module of this code USES the csv.reader method. delimiter='\n' means the delimiter is a newline character, quotechar=" "means the reference character is a space, quoting= csv.QUOTE_NONNUMERIC means that reader converts the unreferenced region to float type, and writer refers to the non-numeric field with a character.

Reference: https: / / docs. python. org / 3 / library csv. html

How to use 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 contents of testcsv.txt are then written to the resultcsv.txt file

The code is as follows:

""" Chapter 15 of Beginning Programming With Python - For Dummies   """
import csv
class 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)
      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:
      print("Data read!")
      return Output

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.

Related articles: