奇怪的文字连接
问题描述:
当我连接时,我得到奇怪的输出。 当它使用这个:奇怪的文字连接
print 'sadasdadgdsfdajfhdsgsdkjhgsfjhdfdsfds'+'.323232600656520346403'
它工作正常。
,但是当我这样做:
getReference = open('test.txt','r')
for line in getReference:#os.path.exists(''+line+'.txt')
try:
with open(''+line+'.txt') as f: pass
except IOError as e:
newURL ='http://www.intrat.th/'+''.join(line)+'.fsta'
print newURL
当我打印的newURL它不给我一个行的文本,而是它有.fsta在第二行。 这是为什么发生?
答
您行:
for line in getReference:
将遍历文件中的行,包括换行符\ n(和\ r)。 因此,您可能试图打开文件'filename \ n.txt',这不是您的意思。
由于作为解决方案,使用带:
with open(''+line.strip()+'.txt') as f: pass
答
这是因为line
以换行字符'\n'
结尾。这个固定的
一种方法是:
for line in getReference:
line = line.strip()
# more code manipulating line
# print stuff
+0
感谢@ inspectorG4dget ..现在的工作 – 2012-07-09 18:01:21
答
听起来你在换行字符阅读。请尝试以下操作:
getReference = open('test.txt','r')
for line in getReference:#os.path.exists(''+line+'.txt')
line = line.rstrip('\n') # Strip the newline here
try:
with open(''+line+'.txt') as f: pass
except IOError as e:
newURL ='http://www.intrat.th/'+''.join(line)+'.fsta'
print newURL
注意,换行分隔符可能不适合你的操作系统是正确的,在这种情况下,你可以做
import os
# all your code
line = line.rstrip(os.linesep)
# more code
+0
谢谢你这么多@thegrinner – 2012-07-09 18:07:36
谢谢@Andre百隆 – 2012-07-09 18:07:50