简体   繁体   English

Python写文件为空

[英]Python write file empty

I'm trying to write a script to convert an Intel HEX file to a Verilog mem format. 我正在尝试编写一个脚本,将Intel HEX文件转换为Verilog mem格式。 I can print the strings I want to save OK (eg the read & parse bit's working) but when I try to write to a file nothing ever appears :( 我可以打印要保存的字符串(例如,读取和解析位有效),但是当我尝试写入文件时,什么也没出现:(

ihexf = open("test.hex","r")
vmemf = open("test.mem","w")

for line in ihexf:
    rlen_s = line[1:3]
    addr_s = line[3:7]
    rtyp_s = line[7:9]
    rlen = int(rlen_s, 16)
    addr = int(addr_s, 16)
    rtyp = int(rtyp_s, 16)
#    print(rlen_s,addr_s,rtyp_s)

    if rtyp == 0:
#        print('@'+addr_s)
        vmemf.write('@'+addr_s+'\n')
        for i in range (0, rlen):
            laddr = addr + i
            val_s = line[9+i*2:9+i*2+2]
            val = int(val_s, 16)
#            print(val_s)
            vmemf.write(val_s+'\n')            
#        print("")
    else:
        print("------- End Of File ------")
ihexf.close()
vmemf.close()

My test.hex looks like 我的test.hex看起来像

:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000FF000000FF000000FF555540FF0A
:20000800155540FF055540FF015540FF005540FF001540FF000540FF000140FF000040FF56
:20001000000040FF000140FF000540FF001540FF005540FF015540FF055540FF155540FF4E
:00000001FF

Any clues what I'm doing wrong? 任何提示我在做什么错?

确保已关闭文件,并且非常重要的是,将文件指针重新定位到文件的开头并开始读取块。

ihexf.seek(0,0)

OK - I worked out what was happening (I think!) 好-我知道发生了什么(我想!)

Existing code works on linux but not Windows. 现有代码可在linux上运行,但不适用于Windows。 On Windows I was seeing the following once the script finished: 在Windows上,脚本完成后,我会看到以下内容:

@0000
@0008
@0010
@0018
------- End Of File ------
Traceback (most recent call last):
File "C:\Users\Nigel\SkyDrive\Files\python\intexhex2v.py", line 8, in <module>
rlen = int(rlen_s, 16)
ValueError: invalid literal for int() with base 16: ''`

Looks like things were messing up at the end of the file read. 在读取文件的末尾看起来有些混乱。

Adding break after the End-Of-File print fixed everything 在文件结束打印后添加break可修复所有问题

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM