use*_*818 1 python file indentation
我是使用python开发的新手,我进行了很好的搜索,以查看是否可以在发布此内容之前回答我的问题,但是我的搜索空白。
我正在打开一个带有随机缩进的文件,我想搜索该文件以找到特定的行,然后将其写入另一个文件中。为此,我正在使用:
with open("test.txt", "r+") as in_file:
buf = in_file.read().strip()
in_file.close()
out_file = open("output.txt", "w+")
for line in buf:
if line.startswith("specific-line"):
newline == line + "-found!"
out_file.append(newline)
out_file.close()
Run Code Online (Sandbox Code Playgroud)
当我的代码加载并读取文件时没有任何问题时,我正在努力解决的问题是如何忽略“ test.txt”文件中的缩进。
例如:
我可能有。
ignore this line
ignore this line
specific-line one
specific-line two
ignore this line
specific-line three
specific-line four
specific-line five
ignore this line
ignore this line
Run Code Online (Sandbox Code Playgroud)
在我的档案中。
就目前而言,我的代码只会找到以“ specific-line ” 开头并在其中包含“ 1 ”,“ 2 ”和“ 4 ”的行。
我需要对我的代码做些什么来更改它,以便我也获得带有“ 特定行 ”加上“ 三 ”和“ 五 ”的行,但是忽略其他任何行(标记为-' 忽略此行)我不想的')行。
谁能帮我?
谢谢!=]
您有两个问题,与中的阅读方式有关in_file。该行:
buf = in_file.read().strip()
Run Code Online (Sandbox Code Playgroud)
只会strip从整个文件的开头和结尾开始留空格,然后:
for line in buf:
Run Code Online (Sandbox Code Playgroud)
实际上是在遍历字符。另外,close如果您使用,则不需要with。
相反,请尝试:
with open("test.txt") as in_file, open("output.txt", "w+") as out_file:
for line in map(str.strip, in_file):
if line.startswith(...):
...
Run Code Online (Sandbox Code Playgroud)
此外,正如Brionius评论中指出的那样,您正在比较(==)而不是将(=)分配给newline,这将导致NameError。