我在python中遇到write()
的问题,这是我的代码:
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()
,输出如下:
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
问题是'
字符会跳转到下一行。我已经尝试过各种不同的方法来编写它。有什么建议吗?
答案 0 :(得分:1)
从文件读取的行具有终止的换行符。在处理之前使用.strip()
删除前导和尾随空格:
>>> temp # example data
'1,2,3\n'
>>> temp.split(',')
['1', '2', '3\n'] # newline is still present.
>>> temp.strip().split(',')
['1', '2', '3']
答案 1 :(得分:0)
您的问题是filters
具有文本文件中的换行符。您实际上是在第一个write
中看到了这一点:
SELECT MATCHID,AVG(CI) AS CI_AV into mydb.CI_ACS/WFC_F625W <- newline here from filters
from detailedcatalog
解决方案是使用strip
or one of its variants to remove the newline。使用strip
后,如果您想要换行符,则需要在第一个\n
的末尾添加换行符write
。