[关闭]
@betasy 2014-12-08T04:43:38.000000Z 字数 4466 阅读 2319

使用Python进行数据流读写的实验

Python 数据流 实验


在本实验中主要对已经生成的ASCII文本大文件进行读写实验,目的是完成对图像转换成的ASCII文件进行类似栅格图像的坐标指定存取。最终形成一个文件读取类,可以将ASCII文件读写封装为如同栅格文件对象一样。
主要处理步骤:
1.序列化ASCII
将ArcMap转换成的ASCII码文件序列化为一列,x×y行的文本文件或.dat文件。方法为
file_stream():

  1. def file_stream(inpath, outpath, offset=6):
  2. """
  3. :param inpath:
  4. :param outpath:
  5. :param offset:
  6. :type offset: int
  7. :rtype : None
  8. """
  9. f = open(inpath, 'r')
  10. s = open(outpath, 'a')
  11. try:
  12. for i in xrange(offset):
  13. f.next()
  14. while True:
  15. ff = f.next()
  16. fi = iter(ff)
  17. try:
  18. while True:
  19. fn = fi.next()
  20. if fn != "\n":
  21. if fn == " ":
  22. s.write("\n")
  23. else:
  24. s.write(fn)
  25. except StopIteration:
  26. pass
  27. except StopIteration:
  28. pass

2.处理ASCII码文件的一些方法

  1. __author__ = 'Administrator'
  2. import arcpy
  3. from arcpy import Raster
  4. out_tmp_path = r'C:\Temp'
  5. def RasterToASCII(raster_path, out_ascii_name):
  6. try:
  7. start = Raster(raster_path)
  8. arcpy.RasterToASCII_conversion(start, out_tmp_path + out_ascii_name)
  9. except SystemError:
  10. print 'Conversion Failed!'
  11. return open(out_tmp_path + out_ascii_name, 'r')
  12. def ASCIIToRaster(ascii_path, origin_raster_path, out_raster_name):
  13. write_in = open(ascii_path, 'r')
  14. out_ascii = open(out_tmp_path + '\\' + out_raster_name + '.txt', 'w+')
  15. raster_props = RasterProperties(origin_raster_path)
  16. out_ascii.write('ncols' + ' ' * 9 + str(raster_props['width']) + '\n')
  17. out_ascii.write('nrows' + ' ' * 9 + str(raster_props['height']) + '\n')
  18. out_ascii.write('xllcorner' + ' ' * 5 + str(raster_props['extent'].XMin) + '\n')
  19. out_ascii.write('yllcorner' + ' ' * 5 + str(raster_props['extent'].YMin) + '\n')
  20. out_ascii.write('cellsize' + ' ' * 6 + str(raster_props['meanCellHeight']) + '\n')
  21. out_ascii.write('NODATA_value' + ' ' * 2 + str(raster_props['noDataValue']) + '\n')
  22. del raster_props
  23. for line in write_in:
  24. in_word = int(line)
  25. out_ascii.write(str(in_word) + ' ')
  26. del write_in
  27. out_ascii.close()
  28. try:
  29. tmp_ascii_path = out_tmp_path + '\\' + out_raster_name + '.txt'
  30. out_raster = out_tmp_path + '\\' + out_raster_name + '.tif'
  31. print 'out_raster:', out_raster
  32. print 'tmp_ascii_path', tmp_ascii_path
  33. arcpy.ASCIIToRaster_conversion(tmp_ascii_path, out_raster, "INTEGER")
  34. except:
  35. print "Conversion Failed!"
  36. def file_stream(inpath, outpath, offset=6):
  37. """
  38. :param inpath:
  39. :param outpath:
  40. :param offset:
  41. :type offset: int
  42. :rtype : None
  43. """
  44. f = open(inpath, 'r')
  45. s = open(outpath, 'a')
  46. try:
  47. for i in xrange(offset):
  48. f.next()
  49. while True:
  50. ff = f.next()
  51. fi = iter(ff)
  52. try:
  53. while True:
  54. fn = fi.next()
  55. if fn != "\n":
  56. if fn == " ":
  57. s.write("\n")
  58. else:
  59. s.write(fn)
  60. except StopIteration:
  61. pass
  62. except StopIteration:
  63. pass
  64. s.close()
  65. r = open(outpath,'r')
  66. return r
  67. def RasterProperties(raster_path):
  68. raster = Raster(raster_path)
  69. raster_props = {
  70. 'bandCount': raster.bandCount, \
  71. 'catalogPath': raster.catalogPath, \
  72. 'compressionType': raster.compressionType, \
  73. 'extent': raster.extent,\
  74. 'format': raster.format, \
  75. 'hasRAT': raster.hasRAT, \
  76. 'height': raster.height, \
  77. 'isInteger': raster.isInteger, \
  78. 'maximum': raster.maximum, \
  79. 'mean': raster.mean, \
  80. 'meanCellHeight': raster.meanCellHeight,\
  81. 'meanCellWidth': raster.meanCellWidth, \
  82. 'minimum': raster.minimum, \
  83. 'name': raster.name, \
  84. 'noDataValue': raster.noDataValue, \
  85. 'path': raster.path, \
  86. 'pixelType': raster.pixelType, \
  87. 'spatialReference': raster.spatialReference,\
  88. 'standardDeviation': raster.standardDeviation,\
  89. 'uncompressedSize': raster.uncompressedSize, \
  90. 'width': raster.width}
  91. return raster_props

3.任意读取某行数据。暂行使用方法get_line(),这个方法将在后期作为一个ASCII码文件类的方法封装。

  1. def get_line(file_path, x, y):
  2. """
  3. :type y: int
  4. :type x: int
  5. :type file_path: string
  6. :rtype line: int
  7. """
  8. f = open(file_path, 'r')
  9. line_num = x * y
  10. for i in xrange(line_num - 1):
  11. f.next()
  12. line = int(f.next())
  13. return line

4.ASCII码文件类。
分析:
一个ASCII码文件类应包括

属性 文件名file_name,文件打开模式open_mode,单行字符串长度line_length,值域domain
方法 打开文件指针open_file,读任意行(传参数x,yget_line,写任意行write_line,删除禁止abandon_delete
  1. # coding=utf-8
  2. __author__ = 'Administrator'
  3. filename = r'I:\data\testdata\modify.txt'
  4. openmode='r'
  5. class Data(object):
  6. def __init__(self, file_name, open_mode, *relate_raster):
  7. """
  8. :type self: class
  9. """
  10. self.file_name = file_name
  11. self.open_mode = open_mode
  12. if relate_raster is not None:
  13. self.raster = relate_raster
  14. else:
  15. self.raster = None
  16. self.file = open(self.file_name, self.open_mode)
  17. f = self.file
  18. self.domain = self.cal_domain(f)
  19. self.line_length = self.cal_length(f)
  20. @staticmethod
  21. def cal_length(f):
  22. """
  23. :rtype : int
  24. """
  25. line1 = len(f.readline())
  26. for line in f:
  27. if len(line) > line1:
  28. line1 = int(len(line))
  29. f.seek(0,0)
  30. return line1
  31. @staticmethod
  32. def cal_domain(f):
  33. """
  34. :rtype : tuple
  35. """
  36. min = 0
  37. max = 0
  38. for line in f:
  39. if int(line) < min:
  40. min = int(line)
  41. if int(line) > max:
  42. max = int(line)
  43. domain = (min, max)
  44. f.seek(0,0)
  45. return domain
  46. def get_line(self, x, y):
  47. """
  48. # 应该实现指针移动访问,这里实现了文件迭代访问,需要多次迭代,耗费大量时间。
  49. :type self: class
  50. """
  51. assert isinstance(self.line_length, int)
  52. line_num = self.line_length * x + y + 1
  53. for i in xrange(line_num - 1):
  54. self.file.next()
  55. one_line = int(self.file.next())
  56. assert isinstance(one_line, int)
  57. return one_line
  58. '''
  59. if __name__ == '__main__':
  60. a = Data(filename, openmode)
  61. print a.file_name
  62. print a.line_length
  63. print a.domain
  64. '''
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注