【问题标题】:Python ignores a certain functions write propertiesPython忽略某些函数写入属性
【发布时间】:2018-02-13 11:07:12
【问题描述】:

我创建了一个包含 4 个函数的 python 脚本:

create_dir()
create_list()
create_logic()
create_email()

我可以使用如下批处理文件单独运行每个脚本:

REM:: Start.bat

@echo off
c:\python27\python create_dir.py
SLEEP 1
c:\python27\python create_list.py
SLEEP 1
c:\python27\python create_logic.py
SLEEP 1
c:\python27\python create_email.py
pause

现在我创建了 1 个 python 脚本,将之前的每个脚本作为一个函数。

问题出在create_logic() 函数上。当我从
if __name__ == '__main__': 调用脚本时,create_logic() 函数不会创建文件 non_existing.txt 并写入文件。 然而所有其他脚本都各司其职..

事实上,看起来程序只是跳过了告诉脚本创建文件并写入文件的行。

下面是问题部分。 non_existing.txt 没有在脚本中创建,我不知道为什么,任何建议或解释将不胜感激。

#print the non matching lines   
f1=open('non_existing.txt', 'a')
f1.write('This ' + nomatch + ' does not exist in the list' +'\n')
f1.close() 

下面的完整脚本:

import os
from fnmatch import fnmatch
import sys
import datetime
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders

def create_dir():

    root = 'C:\\Users\\foo\\bar1'
    pattern = '*.jpg'
    #print all .jpg to fileX.txt
    with open('fileX.txt', 'w') as a:
        for path, subdirs, files in os.walk(root):
           for filename in files:
                if fnmatch(filename,pattern):
                    a.write(str(os.path.join(filename)) + '\n')

def create_list():

    tm = time.strftime('%Y%m%d')
    now = datetime.datetime.now()
    file_prefix = 'fileY'
    #future use...
    #sys.stdout = open(file_prefix+now.strftime('%Y%m%d-%H%M%S')+'.txt', "w")
    sys.stdout = open(file_prefix + '.txt', 'w')
    textprefix = ''
    textsuffix =  '_' + tm
    counter = 1
    #fill in range
    myRange = range(0,100)
    for count in myRange:
    #fill in abount of zeroes
        print textprefix + str(counter).zfill(5) + textsuffix
        counter += 1

def create_logic():
    #load lines from file into lists
    lines1 = [line1.rstrip('\n') for line1 in open('fileX.txt')]
    lines2 = [line2.rstrip('\n') for line2 in open('fileY.txt')]
    #set lines
    set_of_lines1 = set(lines1)
    set_of_lines2 = set(lines2)
    #set common
    common = set_of_lines1 & set_of_lines2
    #return lines which partially match as variable e
    partial_match = [e for e in lines1 if e.startswith(tuple(lines2))]
    matches = []
    for prefix in lines2:
        for snap in lines1:
            if snap.startswith(prefix):
                matches.append(prefix)
    #minus partially matched lines from fileY.txt
    for nomatch in set(lines2) - set(matches):
    #print the non matching lines   
        f1=open('non_existing.txt', 'a')
        f1.write('This ' + nomatch + ' does not exist in the list' +'\n')
        f1.close() 


def create_email():
    #date time settings
    Timt = time.strftime(' %H:%M')
    Datet = time.strftime('%A, %d_%B_%Y')  
    #address
    fromaddr = 'test@test.com'
    toaddr = 'test@test.com'
    #message 
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr
    msg['Subject'] = 'non existing'
    body = 'Attached is non_existing. Sent on the ' + Datet + Timt
    msg.attach(MIMEText(body, 'plain'))
    #attachement 
    filename = 'non_existing.txt'
    attachment = open('C:\\Users\\foo\\bar\\attachment_folder\\non_existing.txt', 'rb')
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
    msg.attach(part)
    #server details
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, 'p@$$word')
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()   


if __name__ == '__main__':
    create_dir()
    create_list()
    create_logic()
    create_email()  

【问题讨论】:

  • 大概,set(lines2) - set(matches) 会产生一个空集,因此 for 循环不会运行。
  • @DanielRoseman 谢谢我能做些什么来证明这一点我可以制作 1 个变量并查看它是否打印?喜欢for nomatch in set(lines2):

标签: python windows python-2.7 file printing


【解决方案1】:

当 for 循环不运行时(即set(lines2)-set(matches) 为空),您的文件不会被创建。如果您希望在任何情况下都创建文件(即使在您的函数之后它是空的),您可以这样做:

f1=open('non_existing.txt', 'a')
for nomatch in set(lines2) - set(matches):
#print the non matching lines   
    f1.write('This ' + nomatch + ' does not exist in the list' +'\n')
f1.close()

这些是文本文件 fileX.txt 中的lines1

00001_20180218_061738.jpg
00002_20180218_061749.jpg
00003_20180218_061751.jpg
00005_20180218_061752.jpg

这些是文本文件fileY.txt中的lines2

00001_20180218
00002_20180218
00003_20180218
00004_20180218
00005_20180218

然后以这种格式设置它们:

第 1 行:

lines1 = set('00001_20180218_061738.jpg', '00002_20180218_061749.jpg', '00003_20180218_061751.jpg', '00005_20180218_061752.jpg')

行2:

lines2 = set('00001_20180218', '00002_20180218', '00003_20180218', '00004_20180218', '00005_20180218')

不匹配 =

'00004_20180218'

【讨论】:

  • 感谢您的回答。我仍在试图理解为什么set(lines2) - set(matches) 会导致一个空集.. 你能给出解释吗?
  • @MALKAVIAN 你能打印lines2 和lines1 吗?所以我可以看到里面有什么?
猜你喜欢
  • 1970-01-01
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多