Python实现自定义数据的文件写入和读取
通常我们需要将处理的数据进行存储和再次的读取,从而让程序工作能够中途保存,下次再加载这些数据继续处理,又或者我们需要用高性能PC机生成一些控制指令,然后将指令文件发送给下位机去执行。
文件一般由三部分组成,文件头(Head),数据(Data),文件结尾(EOF)(End of file)。
访问文件时一定要注意文件路径,当你的工作空间和目标文件处于同一文件夹下时, 可以直接通过文件名访问,如果和目标文件处于不同文件夹,就需要加入路径,否则就找不到目标文件。
关于句尾符号,有两种规定:
ASA(American Standards Association)规定要用CR(\r)和LF(\n)两种字符连续排列表示句尾:\r\n
ISO(International Organization for Standardization) 规定用以上任意一种都行:\n (\r)
这里再介绍下字符编码,字符编码是把计算机中的byte数字转化为字符以,最常见的编码形式有ASCII和UNICODE,同时ASCII智能存储128个字符,而UNICODE最多可以存储高达1,114,112个字符。
事实上文件中的任何一个数,一个字母,一个字,一个标点符号都是以单个或多个字符的形式存储在计算机内存中,如果知道这点,那么在写入文件的时候就应该知道写入的必须是字符变量,同时读取文件的时候读取到的是一个个字符组成的字符串列表。
文件读取所需要用到的参数有:
方法一:
file_object = open(filename, mode = "r")//第一个输入参数是文件名,第二个输入参数是读写形式,返回文件对象
file_object.closed() //用上法打开时要注意用此行命令关闭程序
方法二:
with open(filename, mode = "r") as file_objext //用了with..as..语句,跳出此命令时会自动关闭文件
接下来是代码展示:
写入数据:
#This is the code used to create the commands.txt file
import numpy as np #generate the points pi = np.pi r = 0.1 #devide into suitable levels #actually the radius of the ABS is 1 mm (0.0001 m) levels = int(r/0.01) - 1 #take the 0.01 as a example theta = np.linspace(0,2*pi,60) #generate the list form 0 to 2pi divided in 60 #this need modify according to the perimeter(周长) points_tot_x = [] points_tot_y = [] #create a circle points for l in range(1,levels+1): points_ox = r*np.cos(theta) #create the x coordinate points_oy = r*np.sin(theta) #createt the y coordinate #Here points is equal to 60 num_points = 60 #define the file name filename = "commands.txt" #open the file as a file object with open(filename,'w') as f_obj: #write the px and py parameters #format is followed like tihs: for n in range(0,num_points): f_obj.write("px ") f_obj.write("%.6f"%points_ox[n]) #set the format f_obj.write(" py ") f_obj.write("%.6f"%points_oy[n]) #set the format f_obj.write("\n")
效果展示:
读取数据:
#This is the code used to load the commands.txt file #define the filename filename = "commands.txt" #open the file as a file object with open(filename) as f_obj: #read the file line by line lines = f_obj.readlines() #get the lines number and set a index num_lines = len(lines) points_ox = [] points_oy = [] for line in lines[0:num_lines]: #try to write the code to settle the data if line[3]=='0': points_ox.append(float(line[3:11])) points_oy.append(float(line[15:23])) else: points_ox.append(float(line[3:12])) points_oy.append(float(line[16:24])) print(points_ox) print(points_oy)
效果展示:
(转载请注明出处!!!)