该Python代码的最后一部分是如何工作的?

问题描述

代码的基本作用是获取一个.txt文件,用“ |”替换“” 然后将其替换后,返回并删除以“ |”开头的所有行

我无法理解这段代码的最后一部分。

我了解所有内容,直到:

output = [line for line in txt if not line.startswith("|")]
f.seek(0)
f.write("".join(output))
f.truncate()

代码之前的所有内容^^我了解,但不确定该代码如何执行工作。

--------这是完整的代码------------

# This imports the correct package
import datetime

# this creates "today" as the variable that holds todays date
today = datetime.date.today().strftime("%Y%m%d")

# Read the file
with open(r'\\mlgserver04\mlgshare\DataTransfer&AuditCompliance\ARSI Calls\CallLog_ARSI_' + today + '.txt','r') as file:
   filedata = file.read()

# Replace the target string
filedata = filedata.replace('   ','|')

# Write the file out again
with open(r'\\mlgserver04\mlgshare\DataTransfer&AuditCompliance\ARSI Calls\CallLog_ARSI_' + today + '.txt','w') as file:
   file.write(filedata)

# opens the file
with open(r'\\mlgserver04\mlgshare\DataTransfer&AuditCompliance\ARSI Calls\CallLog_ARSI_' + today + '.txt','r+') as f:
    txt = f.readlines()
    output = [line for line in txt if not line.startswith("|")]
    f.seek(0)
    f.write("".join(output))
    f.truncate()

解决方法

f.read()返回数据blob(字符串或字节) 另一方面,f.readlines()返回字符串或字节的列表。

output = [line for line in txt if not line.startswith("|")]

这跟说的一样

output = []
for line in txt:
  if not line.startswith("|"):
    output.append(line)

因此,创建一个新的字符串列表,其中仅包含我们要保留的字符串。

"".join(output)

Join接受一个可迭代的字符串,并将它们与定界符添加在一起(在本例中为“”)。所以输出[0] +“” +输出[1],依此类推。

最后,将最后一个字符串写回到文件中。