Python:读取和写入小文件的最简单,最安全的方法

时间:2016-01-05 17:53:49

标签: python file

我有一个脚本(除其他外):

  • 读取文件的第一行(十六进制)以将其存储在变量
  • 读取并递增该文件的第二行(dec int)

所以,由于位置等原因,最简单的方法就是不必拉头发。

或者,我应该以不同的方式组织我的文件吗?

3 个答案:

答案 0 :(得分:1)

我认为最好的方法是重写第一行,但我可能错了。

我尝试了 fileinput()(使用 inplace = 1 ,你可以打印到你的文件中),我弄得一团糟。

所以,很大程度上受到了@mid的解决方案的启发,这是我的代码:     #!/ usr / bin / env Python     # - - 编码:utf-8 - -

nom = "chambre"

with open(nom + ".txt", 'r') as file:
    data = file.readlines()

remote = int(data[0], 16)
code = int(data[1])
data[1] = str(code + 1)

print hex(remote)
print code

with open(nom + ".txt", 'w') as file:
    file.writelines(data)

答案 1 :(得分:0)

这解决了您的问题:

with open(SourceFile, 'r') as file:
    data = file.readlines()

print "Your data at line 1" + data[0]
data[1] = "New line to insert instead of the 2nd line\n"

with open(SourceFile, 'w') as file:
    file.writelines( data )

答案 2 :(得分:0)

import io  

firstLine = 0x10  
secondLine = 0x20  

print ("create file")  
file = open('test.txt', 'w')  
file.write(hex(firstLine) + '\n')  
file.write(hex(secondLine) + '\n')  
file.flush()  
file.close()  
file2 = open('test.txt', 'r')  
print ("create file done")  

print ("read file")  
first = file2.readline()  
second = file2.readline()  
firstLineOut = int(first,16)  
print ('First: ', hex(firstLineOut))  
secondLineOut = int(second,16)  
print ('Second: ', hex(secondLineOut))  
file2.close()  

print ("update file")  
secondLineOut += 1  
print ('Second New: ', hex(secondLineOut))  
file2 = open('test.txt', 'w')  
file2.write(hex(firstLineOut) + '\n')  
file2.write(hex(secondLineOut) + '\n')  
file2.flush()  
file2.close()  
print ('done')