我会觉得有点像。 在过去的几天里才开始学习Python。
这是我到目前为止所拥有的
import os
import urllib2
from csv import DictReader
with open('Infodoc 2.txt','r') as infile:
incsv = DictReader(infile)
for row in incsv:
print row['Publisher']
DocIn = row['DocIn']
DocOut = row['DocOut']
WebAddy = row['WebAddy']
def moo():
os.rename(DocIn, DocOut)
file(DocIn, "wb").write(urllib2.urlopen(WebAddy).read())
hosts0 = open(DocIn,"r")
hosts1 = open(DocOut,"r")
lines1 = hosts0.readlines()
for i,lines2 in enumerate(hosts1):
if lines2 != lines1[i]:
print "line ", i, " in hosts1 is different \n"
print lines2
moo()
我的目标是让我的txt文档的每一行都通过我的功能。 这段代码只运行一次,就是这样。我希望它能够通过并拉动每一行并运行它然后转到下一行。 我有一种感觉,我需要将行分成几行并重复某种循环?
如果你能指出我正确的方向,或者给我一个很棒的小故障。
答案 0 :(得分:0)
问题与您定义moo()
的位置有关。正如所写的那样,在你的进口之后
with open('Infodoc 2.txt','r') as infile:
incsv = DictReader(infile)
for row in incsv:
print row['Publisher']
DocIn = row['DocIn']
DocOut = row['DocOut']
WebAddy = row['WebAddy']
运行。循环遍历所有'Infodoc 2.txt
'后,moo()
已定义
def moo():
os.rename(DocIn, DocOut) #the last DocIn and DocOut from your csv file
file(DocIn, "wb").write(urllib2.urlopen(WebAddy).read())
hosts0 = open(DocIn,"r")
hosts1 = open(DocOut,"r")
lines1 = hosts0.readlines()
for i,lines2 in enumerate(hosts1):
if lines2 != lines1[i]:
print "line ", i, " in hosts1 is different \n"
print lines2
之后,您拨打moo()
moo()
moo()
处理'Infodoc 2.txt'
的最后一行(仅最后一行),程序结束。
因此,您只需将moo()
的定义移至某个点,然后稍微修改一下您的文件(它应该DocIn
,DocOut
和{{ 1}}作为参数),并在循环中调用它,就像这样
WebAddy
添加import os
import urllib2
from csv import DictReader
def moo(DocIn, DocOut, WebAddy):
os.rename(DocIn, DocOut)
file(DocIn, "wb").write(urllib2.urlopen(WebAddy).read())
hosts0 = open(DocIn,"r")
hosts1 = open(DocOut,"r")
lines1 = hosts0.readlines()
for i,lines2 in enumerate(hosts1):
if lines2 != lines1[i]:
print "line ", i, " in hosts1 is different \n"
print lines2
with open('Infodoc 2.txt','r') as infile:
incsv = DictReader(infile)
for row in incsv:
print row['Publisher']
DocIn = row['DocIn']
DocOut = row['DocOut']
WebAddy = row['WebAddy']
moo(DocIn, DocOut, WebAddy)
函数可能不是一个坏主意,以防您想要在路上重用main()
(即将模块导入其他地方)。
moo()
最后,使用def main(infodoc):
with open(infodoc,'r') as infile:
incsv = DictReader(infile)
for row in incsv:
print row['Publisher']
DocIn = row['DocIn']
DocOut = row['DocOut']
WebAddy = row['WebAddy']
moo(DocIn, DocOut, WebAddy)
保护它,这样如果/当您导入它时,您的整个脚本都不会运行。最终版本如下所示:
if __name__ == '__main__':