导入模块和写入文件

时间:2014-04-18 23:07:12

标签: python file python-import

我正在尝试将模块导入module1。我一直在收到错误:AttributeError:' Module'对象没有属性'诗。奇怪的是我有一个名为诗的属性。

我尝试打开一个文件(poetry_generator.txt)或创建一个文件,具体取决于它是否存在,但我不知道它是否有效,因为我一直在收到错误。因此,如果有人能够提前告诉我它不会起作用,那就太棒了。注意:当我在代码存在的文件中运行时,模块poetry_generator.py中的代码可以正常工作,但是当我尝试导入它时,我得到了属性错误。请帮忙

#Module1
import poetry_generator


myfile = open("poetry_generator.txt", "w")
myfile.write(poetry_generator.poem)
myfile.close()
print(poetry_generator.poem)

以下是我要导入的模块

#poetry_generator.py

momdescription = input("word that describes your mother:")
shirt_color = input("An unsuitable colour for a t-shirt:")
smell = input("Something that smells:")
friends_name = input("A friend's name:")
wakeup = input("A word that describes how you feel when you first wake up in the morning:")
smallgreen = input("Something small and green:")
madeUpWord = input("A completely made up word:")
rude = input("A word that sounds rude, but isn't:")
fridge = input("Something you'd find in your fridge:")
uglyAnimal = input("An ugly animal:")


poem = print('''See, see the ''', momdescription ,''' sky
marvel at its big ''', shirt_color ,''' depths.
Tell me, ''', friends_name ,'''do you
Wonder why the ''', uglyAnimal ,''' ignores you?
Why its foobly stare
makes you feel ''', wakeup ,'''. 
I can tell you, it is
Worried by your ''', madeUpWord ,''' facial growth
That looks like
A ''', fridge ,'''.
What's more, it knows
Your ''', rude ,''' potting shed
Smells of ''', smallgreen ,'''.
Everything under the big ''', momdescription ,''' sky
Asks why, why do you even bother?
You only charm ''', smell ,'''s.\n''')

1 个答案:

答案 0 :(得分:1)

这是因为您从(poem)导入的模块中的变量poetry_generator没有与之关联的值。您正在为poem变量分配打印功能。而不是实际的字符串本身。

为变量分配打印功能不会保存字符串本身。这就是我的意思:

>>> poem = print("Hi")
Hi
>>> poem
>>>

你需要做

poem = "Hi"

只有这样才能期望poetry_generator.poem能够在其他模块中工作。

使用doc字符串创建输出字符串可能不是一个好的选择。改为创建这样的poem变量:

poem = "See, see the , {} , sky\nmarvel at its big , {} , depths.\nTell me, , {} ,do you\nWonder why the , {} , ignores you?\nWhy its foobly stare\nmakes you feel , {} ,. \nI can tell you, it is\nWorried by your , {} , facial growth\nThat looks like\nA , {} ,.\nWhat's more, it knows\nYour , {} , potting shed\nSmells of , {} ,.\nEverything under the big , {} , sky\nAsks why, why do you even bother?\nYou only charm , {} ,s.\n".format(momdescription, shirt_color, friends_name, uglyAnimal, wakeup, madeUpWord, fridge, rude, smallgreen, momdescription, smell)