[英]Reading from a file into a list and have each element go through the program
Sorry if the title is confusing. 对不起,如果标题令人困惑。 What I want to do is have a text file (keywords.txt) read and then split into a list.
我想要做的是读取一个文本文件(keywords.txt)然后拆分成一个列表。 So basically lets say the file contained "iphone, keys, wallet, pen, folder", I would want the list to be [iphone, keys, wallet, pen, folder].
所以基本上可以说文件包含“iphone,钥匙,钱包,笔,文件夹”,我希望列表是[iphone,钥匙,钱包,笔,文件夹]。
Is there any way to set one variable to work for each element. 有没有办法设置一个变量适用于每个元素。 Say the variable is query.
假设变量是查询。 Is there anyway for query to be each of the elements so it can go through the program and work for each element.
无论如何,查询都是每个元素,因此它可以通过程序并为每个元素工作。 Below is the code I have, it obviously doesnt work but that is what I want to happen if possible.
下面是我的代码,它显然不起作用,但如果可能的话,这就是我想要的。
The reason I want to do it for each is because eventually the script will write a new text file for each of the elements and name it based on what the element is and the only way I know how to do that is by having one variable. 我想为每个元素执行此操作的原因是因为最终脚本将为每个元素编写一个新的文本文件,并根据元素的名称命名它,并且我知道如何执行该操作的唯一方法是使用一个变量。
data = [line.strip() for line in open('keywords.txt', 'r')]
try:
query = sys.argv[1]
except IndexError:
query = item in data
Here is the rest of the code that I will be performing. 以下是我将要执行的其余代码。 It will take what is in the list that is created and create a new textfile and a csv file.
它将采用创建的列表中的内容并创建新的文本文件和csv文件。
newFile = open("%s.txt" %query, 'w').write(txt.encode('utf8'))
with open("%s.txt" %query, 'rb') as input_file:
reader = csv.reader(input_file, delimiter='\n', quoting = csv.QUOTE_NONE)
with open("%s.csv" %query, 'wb') as output_file:
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
Turn the query
value taken from the command line into a list instead, then loop over the query list: 将从命令行获取的
query
值转换为列表,然后遍历查询列表:
try:
query = [sys.argv[1]]
except IndexError:
query = data
for q in query:
# do something with q
def process_keywords_in_file(file_name):
with open(file_name) as f:
for line in f:
process(line.strip())
def process(keyword):
#your code
if you want to write a new file with the name of the keyword: 如果要编写具有关键字名称的新文件:
with open('%s.txt' % keyword, 'w') as fw:
fw.write('content')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.