[英]Trying to copy a set of specific strings from many text files in a directory and paste them in a new text file
I am pretty new to python and I am trying to sort through a directory's files that start with 'O0' and copy any string in the text files that has an 'F', 'T', or 'S' in them, and paste, preferably just that string, (but the whole line would still work) in a new text file, preferably on the desktop.我对 python 很陌生,我正在尝试对以“O0”开头的目录文件进行排序,并复制文本文件中包含“F”、“T”或“S”的任何字符串,然后粘贴,最好只是那个字符串,(但整行仍然可以工作)在一个新的文本文件中,最好是在桌面上。 It is making the text file, but it is blank, and python does not close the file.它正在制作文本文件,但它是空白的,并且 python 不会关闭文件。 Here's what I have so far:这是我到目前为止所拥有的:
import os
# definitions
directory = (r'\directoryname')
feedsspeeds = open('feedsspeeds.txt', 'a+')
# scanning through sub folders
for file in os.scandir(directory):
if file.path.startswith("O0"):
with open(file, 'r') as f:
for line in file:
if ('F', 'T', 'S') in line:
feedsspeeds.append(line)
In the first place you are probably getting an AttributeError
error that append
is not known.首先,您可能会收到append
的AttributeError
错误。 Because you try to append your text to the TextIOwrapper ( feeds speeds
).因为您尝试将您的文本 append 到 TextIOwrapper ( feeds speeds
)。 You have to use the write
method to append the text to the file content.你必须使用write
方法将 append 的文本写入文件内容。
Also note that your file is read and written from the current directory, so ./feedsspeeds.txt
.另请注意,您的文件是从当前目录读取和写入的,因此./feedsspeeds.txt
。 As long as you are not executing this script from you Desktop folder, the file will also not be written there.只要您不从桌面文件夹执行此脚本,该文件也不会被写入那里。
Your problem is with for line in file:
.你的问题是for line in file:
。 You want to loop on f
, not file
.你想循环f
,而不是file
。
As a side note I can foresee a problem with if ('F', 'T', 'S') in line:
.作为旁注,我可以预见if ('F', 'T', 'S') in line:
问题。 The in
operator on a string requires a string as left operand.字符串上的in
运算符需要一个字符串作为左操作数。 You are providing a tuple.您正在提供一个元组。
What you want to do is if 'F' in line or 'T' in line or 'S' in line:
.您要做的是if 'F' in line or 'T' in line or 'S' in line:
。
Warning: untested code警告:未经测试的代码
for file in os.scandir(directory):
if file.path.startswith("O0"):
with open(file, 'r') as f:
for line in f:
for item in line.split(): # by default split() use space as separator
if 'F' in item or 'T' in item or 'S' in item:
feedsspeeds.append(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.