简体   繁体   中英

Having trouble writing output to a file

Below is my code, the problem that I'm working on is to have the output of my program "written to a file whose name is obtained by appending the string _output to the input file name".

What is the correct way of going about doing this?

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()

Here is revised code. Something like this?

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()

Try;

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()

Please refer this post : In Python, is read() , or readlines() faster?

If you want to print the output to a new file then;

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()

Now no need to open the first html file read/write use

f = open(fileName, 'r')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM