[英]Python: Compare first line of files and save their path
I'm trying to get my script to read the first line of each file on the parent folder looking for a flag, so It knows how to process them later. 我正在尝试让我的脚本读取父文件夹中每个文件的第一行以查找标志,因此它知道以后如何处理它们。 This code does read the first line of each file (I checked printing them), but the
if
statements don't work. 这段代码确实读取了每个文件的第一行(我检查过打印它们),但是
if
语句不起作用。
for file in os.listdir(".."):
if file.endswith('.txt'):
with open(os.path.join('..\\',file)) as tempfile:
if tempfile.readline().strip() == '//Q':
QFile = os.path.join('..\\',file)
if tempfile.readline().strip() == '//H':
HFile = os.path.join('..\\',file)
I'm not sure if that's the correct way to save the path afterwards, but the issue is on the if
d, since print
statements (not included here) inside either them are never triggered, even though the files are being read correctly. 我不确定这是否是以后保存路径的正确方法,但是问题在于
if
d,因为即使其中的文件正在正确读取,它们中的print
语句(此处未包括)也不会被触发。 Printing their readline.strip()
values, displays the flags as expected. 打印它们的
readline.strip()
值,按预期显示标志。
Right now the test files are simple .txt with //Q
or //H
on the fist line and a bunch of stuff that will be sorted and stored afterwards. 现在,测试文件是简单的.txt文件,第一行带有
//Q
或//H
,以及一堆东西,这些东西随后将进行排序和存储。
I believe that your problem is in reading the first two lines of the file: your //H
comparison advances the file descriptor. 我认为您的问题在于读取文件的前两行:
//H
比较会提高文件描述符的速度。 Also, you assume that the flag is the entire line. 同样,您假定该标志是整行。 Instead ...
相反...
with open(os.path.join('..\\',file)) as tempfile:
first_line = tempfile.readline().strip()
if '//Q' in first_line:
QFile = os.path.join('..\\',file)
elif '//H' in first_line:
HFile = os.path.join('..\\',file)
Does that handle you needs? 可以满足您的需求吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.