[英]With statement being ignored in Python
I have two functions. 我有两个功能。 The first creates a new CSV file (from an existing CSV).
第一个创建一个新的CSV文件(从现有CSV)。 The second appends the same data to the new CSV, but in a slightly different order of the rows.
第二个将相同的数据附加到新的CSV,但行的顺序略有不同。
When I run this together all in one file the first function works but the second does not. 当我在一个文件中一起运行这些文件时,第一个功能有效,而第二个功能则无效。 However when I tried putting the second function in a separate file then calling it in the first script, it did work, albeit I had to enter the input twice.
但是,当我尝试将第二个函数放在单独的文件中然后在第一个脚本中调用它时,它确实起作用了,尽管我不得不输入两次输入。
What do I need to change to get the second function to run properly? 我需要更改什么才能使第二个功能正常运行?
import csv
export = raw_input('>')
new_file = raw_input('>')
ynabfile = open(export, 'rb')
reader = csv.reader(ynabfile)
def create_file():
with open(new_file, 'wb') as result:
writer = csv.writer(result)
for r in reader:
writer.writerow((r[3], r[5], r[6],r[7], r[7],
r[8],r[8],r[9],r[10]))
def append():
with open(new_file, 'ab') as result2:
writer2 = csv.writer(result2)
for i in reader:
writer.writerow((r[3], r[5], r[6], r[7], r[7],
r[8], r[8], r[10], r[9]))
create_file()
append()
I'm new to Python and programming in general, so if there is an all around better way to do this, I'm all ears. 我是Python和程序设计的新手,因此,如果有一种更好的通用方法,我会不胜枚举。
The csv reader has already read the entire file pointed to by ynabfile
, so on the second call (or any subsequent calls) to either create_file
or append
will not be able to fetch any more data using the reader until the file pointer is sent back to the beginning. csv阅读器已经阅读了
ynabfile
指向的整个文件,因此在第二次调用(或任何后续调用) create_file
或append
将无法使用阅读器获取更多数据,直到将文件指针发送回开始。 In your case, a quick fix would be this: 在您的情况下,快速解决方法是:
create_file()
ynabfile.seek(0)
append()
I recommend restructuring your code a bit to avoid pitfalls like this. 我建议您对代码进行一些重组,以避免类似的陷阱。 A few recommendations:
一些建议:
ynabfile
into another list instead, if you can fit the entirety of the file into memory ynabfile
所有内容ynabfile
到另一个列表中 create_file
and append
take parameter of input and output file names create_file
并append
采用输入和输出文件名的参数 ynabfile
in this case), and ensure that it is seeked to the beginning then create a new csv.reader
instance using that. ynabfile
),并确保将其寻找到开头,然后使用该csv.reader
创建一个新的csv.reader
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.