Skip to main content
 首页 » 编程设计

Python写入文件

2025年05月04日9bhlsheji

我在 debian 服务器上运行的小 python 脚本中遇到了一个小问题。

首先它应该做什么:
- 从服务器获取列表 -> 工作
- 转换为真正的字符串列表 -> 工作
- 写入文件 -> 什么都不做...

已经尝试在 python 界面中使用相同的代码 (>>>),它按照应有的方式编写了所有内容。
文件已创建并在其上设置了 chmod 777。
即使不是意外地检查了该 scipt 的另一个实例正在运行,它锁定了文件但什么都没有......

有人知道为什么它不会在启动时写入文件,而是在界面中写入文件吗?

现在这是脚本本身:

#!/usr/bin/env python 
 
import urllib 
import sys 
import time 
import re 
 
exitNodes = [] 
readableNodes = [] 
class BlockTor(): 
    def getListFromWeb(myself): 
        url = "https://www.dan.me.uk/torlist/" 
        #url = "file:///E:/test.txt" 
 
        try: 
            for line in urllib.request.urlopen(url): 
                exitNodes.append(str(line, encoding='utf8')) 
 
            for node in exitNodes: 
                readableNodes.append(re.sub('\\n', '', node)) 
            #print(exitNodes) 
            #sys.exit() 
        except: 
            try: 
                f = open("/var/log/torblocker.log", "a") 
                #f = open("E:\\logfile.log", "a") 
                f.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] Error while loading new tornodes") 
                f.close() 
            except: 
                print("Can't write log") 
                pass 
            sys.exit() 
            pass 
 
 
    def buildList(myself): 
        f = open("/etc/apache2/torlist/tor-ip.conf", "w") 
        #f = open ("E:\\test-ips.conf", "w") 
        f.write('<RequireAll>\n') 
        f.write('   Require all granted\n') 
        for line in readableNodes: 
            f.write('   Require not ip ' + line + '\n') 
        f.write('</RequireAll>') 
        f.close() 
        try: 
            f = open("/var/log/torblocker.log", "a") 
            #f = open("E:\\logfile.log", "a") 
            f.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] Sucessfully updated tor blacklist") 
            f.close() 
        except: 
            pass 
 
 
    def torhandler(myself): 
        BlockTor.getListFromWeb(myself) 
        BlockTor.buildList(myself) 
 
 
if __name__ == "__main__": 
    asdf = BlockTor() 
    BlockTor.torhandler(asdf) 

编辑:
忘了说 - 如果你想测试它要小心:这个服务器每 30 分钟只允许一个请求

请您参考如下方法:

要连接字符串,请使用 + 运算符。 & 是 bitwise AND - 用两个字符串调用它会导致 TypeError:

>>> "[" & "" 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for &: 'str' and 'str' 

你的毯子 except 抑制了那个错误。替换

try: 
    f = open("/var/log/torblocker.log", "a") 
    #f = open("E:\\logfile.log", "a") 
    f.write("[" & time.strftime("%a, %d %b %Y %H:%M") & "] Sucessfully updated tor blacklist") 
    f.close() # ^                                     ^ 
except: 
    pass 

与

with open("/var/log/torblocker.log", "a") as torf: 
    torf.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] " + 
               "Sucessfully updated tor blacklist") 

如果你想在无法写入文件时忽略异常,请用 try .. except IOError: 将其包围。