最近在DragonBoard 410c开发板debain系统上使用python开发了一个文件读取和写入的功能具体代码如下:
# -*- coding: utf-8 -*-
import sys,os
StrFilePath = os.path.dirname(os.path.realpath(__file__))+"testFile.txt"
def WriteToFile(str):
print(StrFilePath+"||"+str)
try:
FileHandle = open(StrFilePath, 'w')
FileHandle.write(str)
FileHandle.close()
finally:
if (FileHandle):
FileHandle.close()
def PrintFile():
try:
FileHandle = open(StrFilePath,"r")
while True:
chunk = FileHandle.readline()
if not chunk:
break
print(StrFilePath+chunk)
FileHandle.close()
finally:
if(FileHandle):
FileHandle.close()
在代码中提供了两个方法
在writeToFile方法中,首先使用open方法以写入的方式打开文件StrFilePath,之后调用write方法将传入的str字符串写入文件中。
在PrintFile方法中,同样使用open方法以只读的方式打开文件StrFilePath,并调用readline方法读取文件内容。
外部只需要通过python文件名来调用这两个方法去读或写入文件即可。