【问题标题】:Having trouble writing output to a file将输出写入文件时遇到问题
【发布时间】:2016-02-19 06:09:17
【问题描述】:

下面是我的代码,我正在处理的问题是让我的程序的输出“写入一个文件,该文件的名称是通过将字符串 _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()

【问题讨论】:

  • 您正在读取而不是写入文件。看看这个:stackoverflow.com/questions/6159900/…
  • 您的问题是如何连接字符串(只需使用+)还是如何写入文件?
  • 我没有得到写入文件的代码,请提供。
  • 您必须以w 模式打开另一个文件。并在该文件对象上调用write。我们可以提供解决方案,但首先尝试您自己,并在此处提供代码。这样我们就可以在写入文件中解决您的问题。
  • open(filename + '_output', 'w')开头

标签: python


【解决方案1】:

试试;

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

【讨论】:

  • 可以用read() 代替readlines() 加入行,不是吗?
  • @cricket_007。谢谢;已更新。
  • 啊,我应该提到我只能使用我们在课堂上学到的函数/语法。我们从来没有学过 truncate 函数。我虽然了解 write 功能,但我应该如何为该输出创建一个新文件?如果我创建一个像 newFileName=raw_input 这样的新变量,然后创建一个名为 fnew 的新文件来读取它会起作用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
相关资源
最近更新 更多