0

I have a problem with write() in python, here is my code:

b=open("/home/thanasis/Dropbox/NoA/CasJobs/statistics_CI/filters.txt",'r')
a=open("/home/thanasis/Dropbox/NoA/CasJobs/statistics_CI/queries_CI.txt",'w')

for line in b:
    temp=line
    detector,filters=temp.split(",")

    a.write("SELECT MATCHID,AVG(CI) AS CI_AV into mydb.CI_%s_%s"  %(detector,filters))
    a.write("from detailedcatalog \n where Detector = '%s' and Filter= '%s'" %(detector,filters))
    a.write("GROUP BY MATCHID\ngo\n")

    a.close()

and the output is the following:

SELECT MATCHID,AVG(CI) AS CI_AV into mydb.CI_ACS/WFC_F625W
from detailedcatalog 
where Detector = 'ACS/WFC' and Filter= 'F625W
'GROUP BY MATCHID
go

The problem is that the ' character jumps to the next line. I've tried all kind of different ways to write it. Any suggestions?

Michał Góral
  • 1,439
  • 2
  • 16
  • 30
than_g
  • 87
  • 8

2 Answers2

1

Lines read from a file have a terminated newline. Use .strip() to remove leading and trailing white space before processing:

>>> temp  # example data
'1,2,3\n'
>>> temp.split(',')
['1', '2', '3\n']            # newline is still present.
>>> temp.strip().split(',')
['1', '2', '3']
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

Your problem is that filters has the newline character from the text file. You are actually seeing this in your first write:

SELECT MATCHID,AVG(CI) AS CI_AV into mydb.CI_ACS/WFC_F625W <- newline here from filters
from detailedcatalog

The solution is to use strip or one of its variants to remove the newline. Once you use strip you will want to add a newline (\n) at the end of the first write if you intend for a newline to be there.

Community
  • 1
  • 1
missimer
  • 4,022
  • 1
  • 19
  • 33