2017-12-10 6 views
0

基本的なTODOリストプログラムを作成しようとしていますが、ファイルからデータを読み戻すことができません。私はファイル内の私のリストの内容を格納することができたが、私は望む結果を得ることはない、私はそれぞれの行を分割しようとしたread()、readline()、そして私のリストに行を追加し、私のリストの各インデックスをインデックス[0]だけとして数えるか、それ以上のものを追加してファイルを新しいリストで上書きすると、データを読み込むときに全く違うことになります。Pythonで文字列のリストをファイルに保存してデータを取得する

#!/usr/bin/python3 

import os 
from time import sleep 
import platform 
import getpass 
import socket 
import netifaces as ni 
from requests import get 

toDoList = [] 
backup = 'TODOlist.txt' 
cwd = os.getcwd() 

def clean(): 
    if platform.system() == "Linux": 
     os.system("clear") 
    else: 
     os.system("cls") 


def printList(givenList): 

     i = 0 
     for task in givenList: 
      print("\n[%d]: %s" % (i, task)) 
      i += 1 
     print('\n') 



def addToList(listToAdd): 
    task = str(input("\n:")) 
    listToAdd.append(task) 
    print('\n[*]Task [%s] has been added successfully' % (task)) 



def removeFromList(listToRemove): 
    iterator = int(input("\nNumero of the task to remove :")) 
    removed = listToRemove[iterator] 
    if len(toDoList) == 1: 
     listToRemove.append('') 

    listToRemove.pop(iterator) 
    print("[*]\nTask [%d]: %s has been removed successfully" % (iterator, removed)) 



def storageFile(filename, listToStore): 
    overwrite = '' 
    if os.path.isfile(filename): 
     while overwrite != 'y' or overwrite != 'n': 
      choice = str(input('\n[!]This will overwrite your already saved list, are you sure? y/n : ')) 
      if choice == 'y': 
       with open(filename, 'w+') as f: 
        for task in listToStore: 
         f.write(task) 
       print('[*]\nDone.') 
       break 

      else: 
       break 
    else: 
     with open(filename, 'w') as f: 
      for task in listToStore: 
       f.write(task) 

     print('\n[*]%s created in %s' % (filename, cwd)) 



def main(): 
    toDoList = [] 
    clean() 


    while True: 
     print("\n---------------Otions------------------") 
     print("1: Print your TODO list") 
     print("2: Add something") 
     print("3: Remove something") 
     print("4: Number of task in your TODO list") 
     print("5: Save your TODO list") 
     print("6: Delete all from your TODO list") 
     print("7: Delete existing backup of your TODO list") 
     print("99: Exit") 

     optChoice = int(input("\nChoice: ")) 

     if optChoice == 1: 
      printList(toDoList) 
     elif optChoice == 2: 
      addToList(toDoList) 
     elif optChoice == 3: 
      removeFromList() 
     elif optChoice == 4: 
      print("[-]\nYour TODO list currently contains %d task(s)" % (len(toDoList))) 
     elif optChoice == 5: 
      storageFile(backup, toDoList) 
     elif optChoice == 6: 
      del toDoList[:] 
      print('\n[*]Done.') 
     elif optChoice == 7: 
      if os.path.isfile(backup): 

       os.remove(backup) 
       print('\n[*]Backup file %s has been removed.' % (backup)) 
      else: 
       print('\n[X]No backup file has been detected') 

     elif optChoice == 99: 
      clean() 
      exit() 


main() 
+0

あなたは「ロード」機能を持っておらず、どこにもロードしていません.... –

+0

私はそれを削除しました。上記のように、私はたくさんの方法でそれを書こうとしました。それを行う正しい方法についての助けを得るために、明らかに私の構文がどこかで間違っていた –

+0

あなたは 'w'で書込みモードでファイルを開くことができます、それはファイルからすべての内容を消去します。あなたのファイルの内容を読むことができ、あなたのファイルの末尾に何かを追加するモード 'a'を追加することができます。 – Gahan

答えて

1

ロードファイル:

def load(data, myPath): 
    with open(myPath, "r") as f: # use r for read 
     return [x.strip() for x in f.readlines()] 

は、各タスクの後に改行を追加するために、あなたのstorageFile(...)を変更:

def storageFile(filename, listToStore): 
    overwrite = '' 
    if os.path.isfile(filename): 
     while overwrite != 'y' or overwrite != 'n': 
      choice = str(input('\n[!]This will overwrite your already saved list, are you sure? y/n : ')) 
      if choice == 'y': 
       with open(filename, 'w') as f: 
        # user a for append, w+ is not a thing 
        # if you switch to 'a' instead you should check for duplicates bevore 
        # saving: Search SO for "list to set" + "pyhton" 
        # else your list will double itself on saving 
        for task in listToStore: 
         f.write(task + "\n") # added a newline here 
       print('[*]\nDone.') 
       break 

      else: 
       break 
    else: 
     with open(filename, 'w') as f: 
      for task in listToStore: 
       f.write(task+ "\n") # added a newline here 

     print('\n[*]%s created in %s' % (filename, cwd)) 

の変更、ファイル存在する場合起動時に自動ロードを含むように、メインちらほら:

def main(): 
    global toDoList # use the global one 
    global backup # use the global one 

    try: 
     toDoList = load(toDoList, backup) 
    except: 
     toDoList = [] 
    clean() 


    while True: 
     # the rest of your main goes here.... 

あなたはメニューの「負荷」を実装する場合は、すでに変更フォーラムをチェックし、まだtoDoListを保存していない検討するかもしれませんファイル内にあるもので置換する前に(すなわち、toDoListが空であるか「ダーティ」でない場合にのみロードを呼び出すことができます)。あなたはisDirty = Falseをフラグとしてグローバルに追加し、addToListファンクションではTrueに設定し、保存する場合にはFalseに設定することができます。


編集:私はあなたのメインでglobalを追加した理由として

myvar = [1,2,3] 
myOtherVar = [5,6,7] 

def Test(): 
    global myOtherVar # so in this scope "myOtherVar" == the global one 
    myvar = []   # shadows the global one with a local one of same name 
    print (myvar)  # prints the local (empty) one 
    print(myOtherVar) # prints the global one 

Test() 
print("---") 
print(myvar) # prints the global one (same scope, no longer shadowed) 

あなたは、同じ名前のローカルリストを使用してグローバルリストを「影の」 - として、それを宣言することにより、 globalは、グローバルスコープで動作し、それをシャドウしません。

+0

ご協力いただきありがとうございます。まだ初心者がいらっしゃいます。 mainでglobalキーワードを使用する理由は?私は、関数の外で宣言されたとき、変数がすでに「グローバル」とみなされていると思った。 –

+0

@ Orion_2.0 Pythonは宣言をしていない。しかし、はい、あなたは 'toDoList'という名前のグローバルスコープにリストを作成しましたが、' main'で 'toDoList = []'を実行すると、ローカルスコープにその名前を持つ新しい空リストを作成し、そのローカル名 "シャドウ"グローバルなものです。関数内から 'toDoList'をグローバルにクリアするには' .clear'メソッドを呼び出します: 'toDoList.clear()'ですが、グローバル名をシャドーしていない場合にのみ機能します関数内で_anywhere_という名前を付けます。 –

関連する問題