I am trying to process several files into a single, merged csv file using python. So far, I have
files = ["file1.txt", "file2.txt", "file3.txt"]
def doSomething(oldfile):
content = []
with open oldfile as file:
content = file.read().splitlines()
file.close()
return content.reverse()
with open("newfile.txt", "w") as file:
w = csv.writer(file, dialect = "excel-tab")
for i in range(0, len(files)):
w. writerows(doSomething(files[i])
file.close()
The new file is being created, but there is nothing in it. I am curious about what is going on.
Thanks!
For starters, list.reverse()
reverses the list in place and doesn't return anything so you're essentially returning None
from your doSomething()
function. You'll actually want to split that into two lines:
content.reverse()
return content
If you want to streamline your code, here's a suggestion:
def doSomething(oldfile):
with open(oldfile, "r") as f:
return reversed(f.read().splitlines())
files = ["file1.txt", "file2.txt", "file3.txt"]
with open("newfile.txt", "wb") as file:
w = csv.writer(file, dialect = "excel-tab")
for current_file in files:
w.writerows(doSomething(current_file))
I think your program crashes for several reasons:
open(..)
is a function , so you cannot write:
with open oldfile as file:
a with
statement for files is used to enforce closing of a file, so file.close()
is actually not necessary.
.reverse()
works inplace : it returns None
, you can use reversed(..)
for that.
You can fix it with:
files = ["file1.txt", "file2.txt", "file3.txt"]
def doSomething(oldfile):
content = []
with as file:
return
with open("newfile.txt", "w") as file:
w = csv.writer(file, dialect = "excel-tab")
w.writerows(doSomething(oldfile))
I also used a for
loop over the list, instead of the indices, since that is more " pythonic ". Furthermore a file
is iterable over its rows. So one can use reversed(file)
to obtain the lines of the file in reverse.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.