我在处理while循环时遇到了错误。我能够输入我想要运行的数字,并将结果正确写入相应的.CSV。一旦该号码的部分运行完毕,它将询问我是否要再次尝试使用新号码。它运行新的数字代码并创建新的.CSV,但文件大小保持在0kb。我认为这与完成后关闭文件有关但我在那里编写了f#.close()。
Ex:选择数字1,#1的代码运行并正确保存.CSV,为另一次运行选择是和新数字(#2),代码#2运行但未正确关闭因此不保存任何信息到第二CSV。
无论我选择第一个或第二个数字,都会发生这种情况。 (例如:首先选择3,运行3次并保存正常。然后选择2并运行但不能正确保存。)
这是我目前的代码:
f1 = file('1.csv', 'rb')
f2 = file('2.csv', 'rb')
f3 = file('3.csv', 'rb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.reader(f3)
number = raw_input("Enter number: ")
while True:
if number == "1":
f4 = file('No_1_Results.csv', 'wb')
c4 = csv.writer(f4)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f4.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #1"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number == "2":
f5 = file('No_2_Results.csv', 'wb')
c5 = csv.writer(f5)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f5.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #2"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number =="3":
f6 = file('No_3_Results.csv', 'wb')
c6 = csv.writer(f6)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f6.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #3"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number is not "1" or "2" or "3":
print "Invalid number selected."
number = raw_input("Please choose a number: ")
continue
f1.close()
f2.close()
f3.close()
注意:在Windows上使用Python 2.6 /仍在学习python -
答案 0 :(得分:4)
很高兴知道你在循环开始时打开的文件描述符(f1,f2,f3)正在做什么。尽管如此,我认为你所遇到的问题与你试图从其中一个文件描述符中读取两次这一事实有关,但是在执行此操作时你并没有重置它们的位置。请看以下内容:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.readlines()
[]
从文件读取后,文件描述符会记住您上次读取的位置。要解决您的问题,您必须执行搜索并转到文件的开头:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.seek(0)
>>> f1.readlines()
['Test reading from a file\n']
我希望这是您的问题,否则您应该在阅读文件时显示您的逻辑。
答案 1 :(得分:0)
import csv
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
def processFile(infname, outfname, perRow):
with open(infname,'rb') as inf, open(outfname,'w') as outf:
incsv = csv.reader(inf)
outcsv = csv.writer(outf)
outcsv.writerows(perRow(row) for row in incsv)
print("{0} -> {1} successful".format(infname, outfname))
def doStuff(row):
# do stuff here
return row
def main():
while True:
name = inp('Enter next file name (or nothing to exit)')
if name.strip():
try:
processFile(name+'.csv', name+'_result.csv', doStuff)
except IOError, e:
print(e)
else:
print("Goodbye.")
break
if __name__=="__main__":
main()
在查看Python: Comparing two CSV files and searching for similar items的链接后,修改我会继续
def readMasterList():
res = {}
with open('masterlist.csv','rb') as inf:
incsv = csv.reader(inf)
head = incsv.next() # skip header row
for rownum,dat in enumerate(incsv):
res[tuple(dat)] = rownum
return res
masterList = readMasterList()
def doStuff(row, _ml=masterList):
key = (row[1], row[3])
try:
rownum = _ml[key]
row.append("FOUND in master list (row {0})".format(rownum))
except KeyError:
row.append("NOT FOUND in master list")
return row