python中的文件到字符串转换

时间:2017-11-07 22:52:11

标签: python python-2.7

dictionary = file . read()

我正在为2017年的密码挑战创建一个密码求解器 我有一个五十八万字的word文档,但我无法在python 2.7.9中将该文件作为字符串 我尝试过很多我在网上看过的内容,比如上面的代码,但无济于事。 我也需要这个易于理解,因为我是python的新手

谢谢!不要否定是建设性的!

这个词来自: http://www.mieliestronk.com/corncob_lowercase.txt

3 个答案:

答案 0 :(得分:0)

您可能应该在网上查阅一些代码示例来读取文件。你需要这样的东西:

fp = open(fname, "r")
lines = fp.readlines()
for line in lines:
   do_something_with_the_lines
fp.close()

答案 1 :(得分:0)

您所要做的就是:

with open("dictionary.txt") as f: # Open the file and save it as "f"
    dictionary = f.read()         # Read the content of the file and save it to "dictionary"

如果您想从网站上阅读,请尝试以下方法:

import urllib2
dictionary = urllib2.urlopen("http://www.mieliestronk.com/corncob_lowercase.txt").read() # Open the website from the url and save its contents to "dictionary"

答案 2 :(得分:-1)

我认为你应该检查一下你正在尝试做什么(http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

这应该有用