这是将列表写入文件的最简洁方法,因为writelines()不插入换行符吗?
file.writelines(["%s\n" % item for item in list])
Run Code Online (Sandbox Code Playgroud)
似乎有一种标准方式......
我想迭代整个文件的每一行.一种方法是通过读取整个文件,将其保存到列表中,然后浏览感兴趣的行.这种方法使用了大量内存,所以我正在寻找替代方案.
我的代码到目前为止:
for each_line in fileinput.input(input_file):
do_something(each_line)
for each_line_again in fileinput.input(input_file):
do_something(each_line_again)
Run Code Online (Sandbox Code Playgroud)
执行此代码会显示错误消息:device active.
有什么建议?
目的是计算成对的字符串相似性,意味着对于文件中的每一行,我想与每隔一行计算Levenshtein距离.
如何使用Python 3搜索和替换文件中的文本?
这是我的代码:
import os
import sys
import fileinput
print ("Text to search for:")
textToSearch = input( "> " )
print ("Text to replace it with:")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch = input( "> " )
#fileToSearch = 'D:\dummy1.txt'
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
if textToSearch in line :
print('Match Found')
else:
print('Match Not Found!!')
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
input( '\n\n Press …Run Code Online (Sandbox Code Playgroud) 这个简单的代码只是试图用冒号替换分号(在i指定的位置)不起作用:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
Run Code Online (Sandbox Code Playgroud)
它给出了错误
line[i]=":"
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
我如何解决这个问题用冒号代替分号?使用replace不起作用,因为该函数不带索引 - 可能有一些我不想替换的分号.
例
在字符串中我可能有任意数量的分号,例如"Hei der !; Hello there;!;"
我知道我想要替换哪些(我在字符串中有他们的索引).使用replace不起作用,因为我无法使用索引.
在Python中,一般而言 - close()对文件对象的flush()操作是否意味着操作?
当我open()在python 2.4.3中使用时,我收到以下错误
File "/tmp/chgjdbcconfig.py", line 16 with open("text.new", "wt") as fout: ^ SyntaxError: invalid syntax
我检查了python版本,这是我的输出
Python 2.4.3
我正在寻找可能替代方案的建议.我正在尝试编辑Linux服务器上的XML文件中的行,我无法控制python版本的升级.
任何建议都会很棒!