Reputation: 117
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?
Upvotes: 0
Views: 1174
Reputation: 4079
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.
Upvotes: 0
Reputation: 177600
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']
Upvotes: 1