下面是我的代码,我正在处理的问题是将我的程序输出#34;写入一个文件,其名称是通过将字符串_output
附加到输入而获得的文件名"。
这样做的正确方法是什么?
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r')
myList = f.readlines()
for i in range(0, len(myList)):
toString = ''.join(myList)
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
print newString #testing the output
f.close()
这是修改后的代码。像这样的东西?
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r')
fnew = open(fileName, 'w')
myList = f.readlines()
for i in range(0, len(myList)):
toString = ''.join(myList)
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
fnew.write(newString)
f.close()
答案 0 :(得分:0)
尝试;
fileName = raw_input('Enter the HTML file name:') + '.html'
f = open(fileName, 'r+')
toString = f.read()
newString = toString.replace('<span>', '')
newString = newString.replace('</span>', '')
print newString #testing the output
f.truncate() #clean all content from the file
f.write(newString) #write to the file
f.close()
请参阅此帖:In Python, is read() , or readlines() faster?
如果要将输出打印到新文件,那么;
new_file = open(new_file_path, 'w') #If the file does not exist, creates a new file for writing
new_file.write(newString)
new_file.close()
现在无需打开第一个html
文件read/write
使用
f = open(fileName, 'r')