我如何使用线路.rstrip

2024-04-18 01:40:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的Python脚本,从服务器下载过时的文件。脚本读取一个日志文件以查看该文件是否已下载,然后决定下载或跳过该文件。你知道吗

如果该文件不在日志文件中(意味着它还没有被下载),那么它将下载该文件并将文件名写入日志。因此,当脚本再次运行时,它不会再次下载文件。你知道吗

如何检查日志中是否存在该文件是通过使用

f = open('testfile.txt', 'r+')
for line in f:
    if line.rstrip() == mysales + date + file:
        mysalesdownload = "TRUE"
    elif line.rstrip() == myproducts + date + file:
        myproductsdownload = "TRUE"
    else:
        continue

mysales+date+文件在日志文件中类似于-mysales\u 2014-05-01.txt。你知道吗

现在的问题是我想在文件中添加一个分隔符(;)和一个下载日期。下载日期告诉我脚本何时下载数据。你知道吗

 f.write( mysales + date + file + ";" + datetime.date.today() + "\n");

但是,这会妨碍我现在读取日志文件。日期是动态的,数据确实在夜间运行。所以,记住这条线现在是这样的:

   mysales_2014-05-01.txt;2014-05-02 

如果脚本在夜间运行,如何只读取分号,这样就不会下载同一个文件两次?你知道吗


Tags: 文件数据服务器txt脚本truefordate
2条回答

如果只想查看文件是否在日志文件中,可以使用in条件:

current_sales = '{}{}{}'.format(my_sales, date, file)
current_products = '{}{}{}'.format(my_products, date, file)
with open('test_file.txt', 'r+') as file:
    for line in file:
        if current_file in line:
            my_sales_download = 'TRUE'
        elif current_products in line:
            my_products_download = 'TRUE'

最后的else语句是多余的,可以去掉。另外,我认为应该谨慎地检查my_sales_downloadmy_products_download是否都是TRUE。如果是这种情况,您可能可以从for循环break。你知道吗

更改此行:

if line.rstrip() == mysales + date + file:

收件人:

if line.rstrip()[:line.rstrip().find(';')] == mysales + date + file:

等等。你知道吗

相关问题 更多 >