【问题标题】:The String is Not Read Fully字符串未完全读取
【发布时间】:2017-01-31 07:39:22
【问题描述】:

我编写了一个程序来生成一个数字字符串,由 0、1、2 和 3 组成,长度为 s,并将输出写入 decode.txt 文件。下面是代码:

import numpy as np

n_one =int(input('Insert the amount of 1: '))
n_two =int(input('Insert the amount of 2: '))
n_three = int(input('Insert the amount of 3: '))
l = n_one+n_two+n_three
n_zero = l+1
s = (2*(n_zero))-1


data = [0]*n_zero + [1]*n_one + [2]*n_two + [3]*n_three
print ("Data string length is %d"  % len(data))

while data[0] == 0 and data[s-1]!=0:
         np.random.shuffle(data)
datastring = ''.join(map(str, data))
datastring = str(int(datastring))
files = open('decode.txt', 'w')
files.write(datastring)
files.close()
print("Data string is : %s " % datastring)

当我尝试从另一个程序读取文件时出现问题,程序不调用字符串的最后一个值。

例如,如果生成的字符串是30112030000,则其他程序只会调用3011203000,即不调用最后的0。

但如果我直接在 .txt 文件中键入 30112030000,则会读取所有值。我不知道我的代码哪里出了问题。

谢谢

【问题讨论】:

    标签: python python-2.7 call file-writing file-read


    【解决方案1】:

    有些程序可能不喜欢文件不以换行符结尾的事实。在关闭之前尝试添加files.write('\n')。

    【讨论】:

    • 我该如何关闭这个q
    • 很高兴它有效!请“接受”我的回答和/或投票。谢谢。
    • 好的就行。但是等等,如果我希望字符串以非零开头并以零结尾,我应该在条件下写什么?
    • 在代码中,我使用了while data[0] == 0 and data[s-1]!=0:,有时有效,有时无效。
    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多