Python将输出写入txt文件并从txt文件中读取

时间:2015-01-24 01:54:20

标签: python

嗨我试图在循环中调用write函数(基本上,write()函数将运行几次)

我为写作写的内容是:

w.write(board+" "+str(number))

这里board是一个字符串(16个字符),number是一个int。我没有添加任何换行符,而w是写入txt文件。

所以我想要的是输出相互跟随,没有插入换行符。但是,当我输出解决方案时,在文本文件中,输出将转移到换行符。

我是否知道write()函数是否有任何内在问题,无论如何我能解决它吗?

def countword(board,dic):
list=[0]*26
for char in board:
    if char == '\n':
        break
    list[ord(char)-97]+=1
number=0
notFound=False
for word in range(0,(len(dic)-1)):
    for i in range(26):
        if (list[i]<dic[word][i]):
            notFound=True
            break
    if notFound==True:
        notFound=False
        continue
    number+=1;
return number



def dict(dictionary):

result=[]
s=open(dictionary,'r')
lines=s.readlines()         
for line in lines:
    if len(line)<3:
        continue
    list=[0]*26
    line=line.lower()
    for char in line:
        if str(char).isalpha():
            list[ord(char)-97]+=1
    result.append(list)
s.close()
return result

f = open('input.txt', 'r')
w = open('output.txt','w')


dic=dict('word_dictionary')
while True:
    board=f.read(16)
    if len(board)<16:
        print("End of file!")
        break
    print (board)
    number=countword(board,dic)

    w.write(board+" "+str(number))
f.close()
w.close()

事实上,当我从文件中读取时,我也遇到了一个问题: 当我用简单的

阅读它们时
board=f.read(16)
print(board)
board=f.read(16)
print(board)  

0 个答案:

没有答案