Python provides an example of how to read and write files in a specific format,
This example describes how to read and write files in a specific format in Python. We will share this with you for your reference. The details are as follows:
#! /Usr/bin/env python # coding = utf-8class ResultFile (object): def _ init _ (self, res): self. res = res def WriteFile (self): fp = open('pre_result.txt ', 'w') print 'write start! 'Try: for item in self. res: fp. write (item ['host']) fp. write ('\ R') fp. write (str (item ['cpu ']) # The real parameter of the write method must be of the string type fp. write ('\ R') fp. write (str (item ['mem ']) fp. write ('\ n') finally: fp. close () print 'write finish! 'Def ReadFile (self): res = [] fp = open('pre_result.txt ', 'R') try: lines = fp. readlines () # Read all data and store finally: fp by row. close () for line in lines: dict ={}# print line. split () # like ['compute21', '2', '4'] line_list = line. split () # by default, dict ['host'] = line_list [0] dict ['cpu '] = int (line_list [1]) slices strings with spaces as separators. # Read the character dict ['mem '] = int (line_list [2]) res. append (dict) return resif _ name _ = '_ main __': Result_list = [{'host': 'compute21', 'cpu ': 2, 'mem': 4}, {'host': 'compute21', 'cpu ': 2, 'mem ': 4}, {'host': 'compute22', 'cpu': 2, 'mem ': 4}, {'host': 'compute23 ', 'cpu ': 2, 'mem': 4}, {'host': 'compute22', 'cpu ': 2, 'mem': 4}, {'host ': 'compute23', 'cpu ': 2, 'mem': 4}, {'host': 'compute24', 'cpu ': 2, 'mem ': 4}] file_handle = ResultFile (result_list) #1. write Data # print 'write start! 'File_handle.writefile () # print 'write finish! '#2. Read data res = file_handle.ReadFile () print res
Written file:
A space is added between the data in each row.
Running result:
write start!write finish![{'mem': 4, 'host': 'compute21', 'cpu': 2}, {'mem': 4, 'host':'compute21', 'cpu': 2}, {'mem': 4, 'host': 'compute22', 'cpu': 2},{'mem': 4, 'host': 'compute23', 'cpu': 2}, {'mem': 4, 'host':'compute22', 'cpu': 2}, {'mem': 4, 'host': 'compute23', 'cpu': 2},{'mem': 4, 'host': 'compute24', 'cpu': 2}]
Write and read data in the original format.