Python文件重定向给出空文件

时间:2017-05-03 15:34:43

标签: python python-2.7

代码用于将数据从十六进制转换为二进制工作完美,但是,当我将输出重定向到文件时,输出文件为空

这是代码

<div ng-app="app" ng-controller="ctrl" ng-init="shown='true'">
  <div class="container">
    <input type="text" />
    <input type="text" class="fade-element-in" ng-if="!shown" />
    <input type="text" class="fade-element-in" ng-if="!shown" />
    <button ng-click="shown=!shown">{{shown}}</button>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

您可以直接写入输出文件,而不是重定向打印输出:

with open("g1.txt.out", "r") as my_file, open("g1.txt.out.binary",'a+') as out_file:
    for line in my_file:
        data_binary = "{0:16b}\n".format(int(line, 16))
        out_file.write(data_binary)

答案 1 :(得分:0)

你需要关闭你的文件,因为io是缓冲的。始终记得关闭所有打开的文件以保存数据。

for file in glob.glob("g1.txt.out"):
    print file
    myfile = open(file, "r")
    outfile= open( file + ".binary",'a+')

    for line in myfile:

        data_binary="{0:16b}".format(int(line, 16))
        print >> outfile,data_binary # redirect code.
    myfile.close()
    outfile.close()

或者更好地学习with语句,它会自动完成。

with open(filename) as f:
    data = f.read()
    do something with data