将信息写入.txt文件并获取None作为我的结果

时间:2015-04-16 03:00:26

标签: python

我在将文件写入学校项目的.txt文件时遇到问题。我已将项目的所有代码都包括在内以供参考。任何输入都将非常感激,但请在python中让初学者理解输入。

def first_letter_count(word, letter):
    for  number in word:
        if number[:1] in letter:
            return True
        else:
            return False

def check(letter):
    letter_count = 0
    fin = open('words.txt')
    for line in fin:
        word = line.strip()
        if first_letter_count(word, letter):
            letter_count += 1
    print str(letter) + ": " + str(letter_count) 


alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
oldstdout = sys.stdout
newfile = open('words_writing.txt', 'w')
for letter in alphabet:
    newfile.write(str(check(letter)))
newfile.close()
newfile2 = open('words_writing.txt', 'r')

1 个答案:

答案 0 :(得分:1)

当您致电newfile.write(str(check(letter)))时,您正在呼叫newfile.write(None),因为支票不会返回任何内容。而不是print末尾的check语句,请尝试添加return

def first_letter_count(word, letter):
    for  number in word:
        if number[:1] in letter:
            return True
        else:
            return False

def check(letter):
    letter_count = 0
    fin = open('words.txt')
    for line in fin:
        word = line.strip()
        if first_letter_count(word, letter):
            letter_count += 1
    return str(letter) + ": " + str(letter_count) 


alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
oldstdout = sys.stdout
newfile = open('words_writing.txt', 'w')
for letter in alphabet:
    newfile.write(str(check(letter)))
newfile.close()
newfile2 = open('words_writing.txt', 'r')

非返回功能演示:

>>> def multiply(num1, num2):
...     print num1 * num2 #Notice the print, not return
... 
>>> x = multiply(5, 6)
30
>>> print x
None
>>> def multiply(num1, num2):
...     return num1 * num2 #Notice the return this time
... 
>>> x = multiply(5, 6)
>>> print x
30
>>>