Python没有写入文件

时间:2016-04-21 19:06:03

标签: python datetime

我制作一个读取.txt文件的脚本,然后继续使用该信息和日期来创建动态html文件。它在昨天工作,但今天,似乎它不想写任何文件...

这是源代码。

from __future__ import print_function
import httplib2
import os
import io
import shutil
import datetime
import random
import re
from apiclient.http import MediaIoBaseUpload, MediaIoBaseDownload
from datetime import date
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

def filerino():

    daginfo     = str(datetime.datetime.today().weekday())
    ukenr       = (datetime.datetime.today().isocalendar()[1])
    dato        = datetime.date.today()
    day         = datetime.date.today().day
    month       = datetime.date.today().month
    yesterday   = (day - 1)
    tomorrow    = (day +1)
    todayerino  = str(day) + "/" + str(month)
    yesterdayerino = str(yesterday) + "/" + str(month)
    tomorrowerino = str(tomorrow) + "/" + str(month)
    currentweek = (datetime.datetime.today().isocalendar()[1])
    lastweek    = ((datetime.datetime.today().isocalendar()[1]) - 1)
    currentweekerino = "Uke " + str(currentweek)
    lastweekerino = "Uke " + str(lastweek)



    file=open("plan.txt", "r")
    if daginfo == "3":
        daginfo = ("Matte\n" + "Naturfag\n" + "Engelsk\n" + "ToF\n")
        dag = ("Torsdag")
        imorgen = ("Fredag")
    elif daginfo == "0":
        daginfo = ("Samfunnsfag\n" + "Geografi\n" + "Norsk / Engelsk\n")
        dag = ("Mandag")
        imorgen = ("Torsdag")
    elif daginfo == "1":
        daginfo = ("Naturfag\n" + "Spraak\n" + "Engelsk\n" + "Matte\n")
        dag = ("Tirsdag")
        imorgen = ("Onsdag")
    elif daginfo == "2" and ukenr %2 == 0:
        daginfo = ("Gym\n" + "Matte\n" + "Norsk\n")
        dag = ("Onsdag")
        imorgen = ("Torsdag")
    elif daginfo == "2" and ukenr %2 != 0:
        daginfo = ("Gym\n" + "Matte\n")
        dag = ("Onsdag")
        imorgen = ("Torsdag")
    elif daginfo == "4":
        daginfo = ("Spraak\n" + "Norsk\n" + "Engelsk\n" + "ToF\n")
        dag = ("Fredag")
        imorgen = ("Laurdag")
    elif daginfo == "5":
        daginfo = ("Ingen fag idag, siden det er HELG! :D")
        dag = ("Laurdag")
        imorgen = ("Saundag")
    elif daginfo == "6":
        daginfo = ("Ingen fag idag, siden det er HELG! :D")
        dag = ("Saundag")
        imorgen = ("Mandag")


    file=open("plan.txt","r")
    s = file.read()
    dayresult = ((s.split(str(tomorrowerino)))[1].split(str(todayerino))[0]).strip()
    dayresult = dayresult[:dayresult.rfind('\n')]
    lines = re.split("\n", dayresult)
    timeserino = dayresult.count("\n")
    try:

        fagTitle = {}
        for x in range(-1, timeserino):
            x += 1
            fagTitle[x] = lines[x]

        fagContent = {}
        for x in range(-1, timeserino):
            x += 1
            fagContent[x-1] = lines[x]

        if timeserino == 1: #if there is 1 lines within the two dates.
            file=open("/testfolder/index.html", "w")
            file.write("""
           <!doctype html>
           <html lang="en">
           <head>

             <meta charset="utf-8">

             <title>InstaPlan</title>

             <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
             <link rel="stylesheet" href="main.css">
           </head>

           <body>
               <div class="jumbotron" id="nbn">
                 <h1 id="sub">""" + (dag) + """ """ + str(dato.day) + """/""" + str(dato.month) + """ """ + """Uke""" + """ """ + str(ukenr) + """:</h1>
                 <h1 id="mid"><small>""" + (daginfo) + """</small></h1>
               </div>
               <div class="jumbotron" id="nbn">
                 <h1 id="mid"><small>Lekser til """ + (imorgen) + """:</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[0] + """</h1>
                 <h1><small>""" + fagContent[0] + """</small></h1>
               </div>
           </body>
           </html>
           """)
        elif timeserino == 3: #if there are 3 lines within the two dates.
            file=open("/testfolder/index.html", "w")
            file.write("""
           <!doctype html>
           <html lang="en">
           <head>

             <meta charset="utf-8">

             <title>InstaPlan</title>

             <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
             <link rel="stylesheet" href="main.css">
           </head>

           <body>
               <div class="jumbotron" id="nbn">
                 <h1 id="sub">""" + (dag) + """ """ + str(dato.day) + """/""" + str(dato.month) + """ """ + """Uke""" + """ """ + str(ukenr) + """:</h1>
                 <h1 id="mid"><small>""" + (daginfo) + """</small></h1>
               </div>
               <div class="jumbotron" id="nbn">
                 <h1 id="mid"><small>Lekser til """ + (imorgen) + """:</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[0] + """</h1>
                 <h1><small>""" + fagContent[0] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[2] + """</h1>
                 <h1><small>""" + fagContent[2] + """</small></h1>
               </div>
           </body>
           </html>
           """)
        elif timeserino == 5: #if there are 5 lines within the two dates.
            file=open("/testfolder/index.html", "w")
            file.write("""
           <!doctype html>
           <html lang="en">
           <head>

             <meta charset="utf-8">

             <title>InstaPlan</title>

             <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
             <link rel="stylesheet" href="main.css">
           </head>

           <body>
               <div class="jumbotron" id="nbn">
                 <h1 id="sub">""" + (dag) + """ """ + str(dato.day) + """/""" + str(dato.month) + """ """ + """Uke""" + """ """ + str(ukenr) + """:</h1>
                 <h1 id="mid"><small>""" + (daginfo) + """</small></h1>
               </div>
               <div class="jumbotron" id="nbn">
                 <h1 id="mid"><small>Lekser til """ + (imorgen) + """:</small></h1>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[0] + """</h1>
                 <h1><small>""" + fagContent[0] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[2] + """</h1>
                 <h1><small>""" + fagContent[2] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[4] + """</h1>
                 <h1><small>""" + fagContent[4] + """</small></h1>
               </div>
           </body>
           </html>
           """)

        elif timeserino == 7: #if there are 7 lines within the two dates.
            file=open("/testfolder/index.html", "w")
            file.write("""
           <!doctype html>
           <html lang="en">
           <head>

             <meta charset="utf-8">

             <title>InstaPlan</title>

             <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
             <link rel="stylesheet" href="main.css">
           </head>

           <body>
               <div class="jumbotron" id="nbn">
                 <h1 id="sub">""" + (dag) + """ """ + str(dato.day) + """/""" + str(dato.month) + """ """ + """Uke""" + """ """ + str(ukenr) + """:</h1>
                 <h1 id="mid"><small>""" + (daginfo) + """</small></h1>
               </div>
               <div class="jumbotron" id="nbn">
                 <h1 id="mid"><small>Lekser til """ + (imorgen) + """:</small></h1>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[0] + """</h1>
                 <h1><small>""" + fagContent[0] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[2] + """</h1>
                 <h1><small>""" + fagContent[2] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[4] + """</h1>
                 <h1><small>""" + fagContent[4] + """</small></h1>
               </div>
               <div class="jumbotron" id="nbm">
                 <h1 id="sub">""" + fagTitle[6] + """</h1>
                 <h1><small>""" + fagContent[6] + """</small></h1>
               </div>
           </body>
           </html>
           """)
    except IndexError: #if it detects an IndexError because there either aren't any lines between the dates
        file=open("/testfolder/index.html", "w")
        file.write("""
       <!doctype html>
       <html lang="en">
       <head>

         <meta charset="utf-8">

         <title>InstaPlan</title>

         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
         <link rel="stylesheet" href="main.css">
       </head>

       <body>
           <div class="jumbotron" id="nbn">
             <h1 id="sub">""" + (dag) + """ """ + str(dato.day) + """/""" + str(dato.month) + """ """ + """Uke""" + """ """ + str(ukenr) + """:</h1>
             <h1 id="mid"><small>""" + (daginfo) + """</small></h1>
           </div>
           <div class="jumbotron" id="nbn">
             <h1 id="mid"><small>Lekser til """ + (imorgen) + """:</small></h1>
           </div>
           <div class="jumbotron" id="nbm">
             <h1 id="sub">ayylmao</h1>
           </div>
       </body>
       </html>
       """)
if __name__ == '__main__':
    main()
    filerino()

它写入名为index.html的文件。我认为问题出在Try语句中,但我试图删除它并且它没有以任何方式影响它。

谢谢。

2 个答案:

答案 0 :(得分:1)

1)确保它符合任何方案。你没有else条件如下,你的timeserino可能不符合1-7场景中的任何一个

if timeserino == 1:
   # write something
elif timeserino ==2:
   # write something
...
elif timeserino == 7:
   # write something
else:
   write something

2)完成写作后关闭文件

答案 1 :(得分:1)

你的根本问题是你的功能太长而且复杂,你无法调试它(或理解它失败的原因)。

使意图更清晰的简单重构就像经常使用的命名表达式(例如datetime.datetime.today())和使用数组从序列中选择某些东西而不是if-statements的长级联:

today = datetime.datetime.today()
weekday = today.weekday()
dagnavn = ['Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', u'Lørdag', u'Søndag']
dag = dagnavn[weekday]

然后明天可以同样选择:

imorgen = dagnavn[(weekday + 1) % 7]

从if语句中删除了dag和imorgen,可以使用daynames而不是工作日数字以更具描述性的方式分配daginfo

daginfo = {
    'Mandag': "Matte\n" + "Naturfag\n" + "Engelsk\n" + "ToF\n",
    'Tirsdag': "...",
    ...
}[dag]

到目前为止,您的代码是一个&#34; unit&#34;可以独自站立(你似乎通过类似段落的间距本能地理解)。它应该被拉出一个单独的功能,以便原始功能变得更小,更容易推理(一个功能通常不应该长于你可以适应屏幕而不滚动)。函数看起来像:

# dagnavn is a constant and should be defined at module level
dagnavn = ['Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', u'Lørdag', u'Søndag']


def get_schedule(date):
    weekday = date.weekday()
    dag = dagnavn[weekday]
    imorgen = dagnavn[(weekday + 1) % 7]
    daginfo = {
        'Mandag': "Matte\n" + "Naturfag\n" + "Engelsk\n" + "ToF\n",
        ...
    }[dag]
    return dag, imorgen, daginfo

然后你将删除filerino()中的long if语句并将其替换为:

dag, imorgen, daginfo = get_schedule(today)  # still assuming you've created the `today` variable

如果你继续拔出代码&#34;单位&#34;像这样进入他们自己的功能,你最终会得到一个更小的功能来展示你的问题。那个较小的函数就是你通常在SO上的一个问题中发布的(这是代表你的问题的最小代码片段)。