簡體   English   中英

Python-如果文件中的字符串以16開頭

[英]Python - If string in file starts with 16 then

我有一個腳本可以檢查PC上的IP地址並將其寫入PC上的文件-正常工作

import socket
import sys
import requests
import urllib.request
import shutil
import subprocess
from time import sleep
import os
from os import system

# URL for download
URL = 'https://here/app.exe'

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 1))
local_ip_address = s.getsockname()[0]
sys.stdout = open("C:\\Temp\\nw_check.txt", "w+")
print(s.getsockname() [0])

現在我想下一步

檢查文件C:\\ Temp \\ nw_check.txt,如果該文件中的IP地址以116、115、117開頭,則使用我將設置的代理下載上述應用程序。如果它以其他任何內容開頭,則繼續下載

if xxxxxx(xxxxxxxx()).startswith(('116', '115', '117')):
    r = requests.get(URL, stream=True, proxies={'http': 'http://proxy:6547', 'https': 'http://proxy:6547'})
else:
    r = requests.get(URL, stream=True)

sys.stdout = open(“ C:\\ Temp \\ nw_check.txt”,“ w +”)

打印(s.getsockname()[0])

為什么將文件設置為stdout然后進行打印,而不僅僅是直接打印/寫入文件?

with open("C:\\Temp\\nw_check.txt", "w+") as f:
    print(s.getsockname()[0], file=f)
    # of f.write(str(s.getsockname()[0])); f.write('\n')

檢查文件C:\\ Temp \\ nw_check.txt,並且該文件中的IP地址是否以116、115、117開頭

為什么要瀏覽中間文件? 為什么不直接檢查s.getsockname() [0]的結果呢?

撇開:1.如果您使用的是上面的代碼,並且在“ with”下面,或者在其他文件中,請以r模式重新打開該文件,讀取前3個字符,然后檢查這是否是您所需要的尋找:

with open("C:\\Temp\\nw_check.txt", "w+") as f:
    print(s.getsockname()[0], file=f)
with open(fname, 'r') as f:
    if f.read(3) in ('116', '115', '117'):
        # etc…
  1. 或2(如果您使用的是原始代碼)或將其放在上面的with正文中,請執行seek(0)將光標移回文件的開頭,然后讀取前3個字符並進行檢查。
sys.stdout.seek(0)
if f.read(3) in ('116', '115', '117'):
    # etc…

只需再次打開文件並讀取IP地址即可:

with open("C:\\Temp\\nw_check.txt", "r") as ip_file:
    ip_address = ip_file.readline()

if ip_address.startswith(("115", "116", "117")):
        # and so on

可以滿足您需要的一些變化形式應該起作用:

with open("C:\\Temp\\nw_check.txt", "r") as input_file:
    for ip_address in input_file:
        if ip_address.startswith(("115", "116", "117")):
            r = requests.get(URL, stream=True, proxies={'http': 'http://proxy:6547', 'https': 'http://proxy:6547'})
        else:
            r = requests.get(URL, stream=True)

由於您的文件只有一行,因此for循環將只運行一次並退出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM