这里我创建一个程序来创建一个名为current directory + url + system date and time .txt的文件 使用netloc仅从http://www.flipkart.com文件中提取flipkart包含\ n。如何从文件中删除\ n。
class FileHandler(object):
def create_file(self,url):
print 'creating file....'
flipkart = urlparse(url)
filename = flipkart.netloc
#filename = dns.name.from_text(url).split(3)[1].to_text(omit_final_dot=True)
#filename = dns.name.from_text(url).split('www.')[1].to_text(omit_final_dot=True)
#str.split(sep=None, maxsplit=-1)
print 'file is---'
print filename
#filename = url
dir = os.getcwd()
#print 'Current directory path is-'
#print dirPath
date = datetime.datetime.now()
now = date.strftime("%Y-%m-%d %H-%M")
dirPath = os.path.join(dir,filename)
dirPath.replace("\n","-")
#filenameCreated = dirPath + now
filenameCreated = dirPath + now
#filenameCreated = filenameCreated1.splitlines()
print filenameCreated
f = self.openfile(filenameCreated + '.txt', 'a')
#readFile(f)
return f
#self.writeFile(f)
#defining openfunction
def openfile(self,filename,mode):
try:
open(filename,mode)
except Exception, err:
print("File cannot be opened.")
print(str(err))
return
答案 0 :(得分:2)
您可以将.rstrip(' \ n')附加到字符串中以删除换行符。
所以你可以尝试类似的东西:
filename = filename.rstrip('\n')