-3

Hi I'm opening and closing an input and an output file as "infile" and "outfile" and using them in a command line argument to extract specific content from one file to another. However the infile content is a list of integers and as I now know I have to turn them to strings to complete the task...

for lines in infile:
    words=lines.split("\t")
    wated=words[15]
    if wated == "559292":
        dataA.append(str(words[1]))#attempt to write list of integers as strings to file
    outfile.write(dataA+'n')#'+n' apparently needed for this process.

However I keep getting the error:

TypeError:can only concatenate list (not "str") to list

When I try it without the "+'n'":

TypeError: expected a character buffer object
JDurstberger
  • 4,127
  • 8
  • 31
  • 68
cian
  • 59
  • 6

2 Answers2

0

Change to this, if you want to store that list in a file:

....
outfile.write(str(dataA)+'n')#'+n' apparently needed for this process.
....
admix
  • 1,752
  • 3
  • 22
  • 27
  • This will technically work but I don't think it's what he really wants because for an input file of N lines, you're outputting a list with 0-to-N elements, N times, for a total of O(N^2). The output file will be a couple megabytes large if the input file is around a kilobyte. – Kevin Dec 11 '15 at 15:08
0

I'm assuming you only want each words[1] value to appear in the output file once, in which case you can do one of these:

  • don't bother with a list; just write words[1] directly to the file
  • wait until the end of the loop before writing the list to the file

Your current approach seems to be a mix of the above choices, which is no good. I also assume that when you add "n", you are actually trying to add a newline.

for lines in infile:
  words=lines.split("\t")
  wated=words[15]
  if wated == "559292":
    outfile.write(str(words[1])+'\n')

Or

for lines in infile:
  words=lines.split("\t")
  wated=words[15]
  if wated == "559292":
    dataA.append(str(words[1])+'\n')
outfile.writelines(dataA)
Kevin
  • 74,910
  • 12
  • 133
  • 166