2014-12-13 18 views
0

有沒有在「w」或「a」模式下創建文本文件而不打開文本文件的方法?舉例來說,如果我想打開「R」模式下的文件,但該文件不存在,那麼當我趕上IO錯誤我想要一個新的文件被創建 如:在Python中創建新的文本文件?

while flag == True: 
try: 

    # opening src in a+ mode will allow me to read and append to file 
    with open("Class {0} data.txt".format(classNo),"r") as src: 

     # list containing all data from file, one line is one item in list 
     data = src.readlines() 

     for ind,line in enumerate(data): 

      if surname.lower() and firstName.lower() in line.lower(): 
       # overwrite the relevant item in data with the updated score 
       data[ind] = "{0} {1}\n".format(line.rstrip(),score) 
       rewrite = True 

      else: 
       with open("Class {0} data.txt".format(classNo),"a") as src: 
        src.write("{0},{1} : {2}{3} ".format(surname, firstName, score,"\n")) 


    if rewrite == True: 

     # reopen src in write mode and overwrite all the records with the items in data 
     with open("Class {} data.txt".format(classNo),"w") as src: 
      src.writelines(data) 
    flag = False 

except IOError: 
    print("New data file created") 
    # Here I want a new file to be created and assigned to the variable src so when the 
    # while loop iterates for the second time the file should successfully open 
+0

http://stackoverflow.com/questions/10978869/safely-create-a-file-if-and-only-if-it-does-not-exist-with-python檢查出來 – aerokite 2014-12-13 16:20:27

+0

這實際上是錯誤的。但是你可以在linux系統的'輸入操作系統; os.system('touch test.txt')' – 2014-12-13 16:21:46

+0

ahh我想解決的辦法是在w模式下創建一個文件,然後關閉它 – joyalrj22 2014-12-13 16:31:55

回答

0

在開始的時候只是檢查文件存在,並且如果它不創建它:

filename = "Class {0} data.txt" 
if not os.path.isfile(filename): 
    open(filename, 'w').close() 

從這一點上,你可以假設該文件存在,這將大大簡化你的代碼。

0

沒有操作系統將允許您創建一個文件,而不實際寫入它。您可以將其封裝在庫中,以便創建不可見,但如果您真的想修改文件系統,則不可能避免寫入文件系統。

這是一個快速和骯髒的open替代,這是你的建議。

def open_for_reading_create_if_missing(filename): 
    try: 
     handle = open(filename, 'r') 
    except IOError: 
     with open(filename, 'w') as f: 
      pass 
     handle = open(filename, 'r') 
    return handle 
0

如果該文件不存在,例如創建文件,則更好。喜歡的東西:

import sys, os 
def ensure_file_exists(file_name): 
    """ Make sure that I file with the given name exists """ 
    (the_dir, fname) = os.path.split(file_name) 
    if not os.path.exists(the_dir): 
     sys.mkdirs(the_dir) # This may give an exception if the directory cannot be made. 
    if not os.path.exists(file_name): 
     open(file_name, 'w').close() 

你甚至可以有一個safe_open功能沒有開放供讀取和返回的文件句柄之前,類似的東西。

0

問題中提供的示例代碼不是很清楚,特別是因爲它調用了多個未定義的變量。但基於它,這是我的建議。您可以創建類似於touch +文件打開的功能,但是這將是平臺不可知的。

def touch_open(filename): 
    try: 
     connect = open(filename, "r") 
    except IOError: 
     connect = open(filename, "a") 
     connect.close() 
     connect = open(filename, "r") 
    return connect 

此功能將爲您打開文件,如果它存在。如果該文件不存在,它將創建一個具有相同名稱的空白文件並將其打開。與import os; os.system('touch test.txt')相比,額外的獎勵功能是它不會在shell中創建子進程,從而使其更快。

由於它不使用with open(filename) as src語法,您應該記得在末尾關閉連接connection = touch_open(filename); connection.close()或者最好可以在for循環中打開它。例如:

file2open = "test.txt" 
for i, row in enumerate(touch_open(file2open)): 
    print i, row, # print the line number and content 

此選項應首選data = src.readlines()其次enumerate(data),在你的代碼中發現,因爲它避免了通過文件循環的兩倍。