我剛剛開始使用Python編寫第一個合適的項目,該代碼片段存儲程序。 爲此,我需要先將多行寫入.txt文件,然後再讀取。我做了很多搜索,並發現了一些關於寫入文件的信息(這並沒有真正起作用)。我目前正在工作的是一個函數,它讀取多行輸入的每一行,並將其寫入列表中,然後將其寫入文件。我曾經想過,我只能從文本文件中讀取它,並將每行添加到列表中,然後使用while循環分別打印每行,但不幸的是這些行不起作用。 經過和做更多的研究,我決定在這裏問。這是代碼我目前:將多行寫入文件,然後用Python讀取它們
'''
Project created to store useful code snippets, prehaps one day it will evolve
into something goregous, but, for now it's just a simple archiver/library
'''
#!/usr/local/bin/python
import sys, os, curses
os.system("clear")
Menu ="""
#----------- Main Menu ---------#
# 1. Create or edit a snippet #
# 2. Read a snippet #
# 0. Quit #
#-------------------------------#
\n
"""
CreateMenu ="""
#-------------- Creation and deletion --------------#
# 1. Create a snippet #
# 2. Edit a snippet #
# 3. Delete a snippet (Will ask for validation) #
# 0. Go back #
#---------------------------------------------------#
\n
"""
ReadMenu="""
#------ Read a snippet ------#
# 1. Enter Snippet name #
# 2. List alphabetically #
# 3. Extra #
# 0. Go Back #
#----------------------------#
"""
def readFileLoop(usrChoice, directory):
count = 0
if usrChoice == 'y' or 'n':
if usrChoice == 'y':
f = open(directory, 'r')
text = f.read()
f.close()
length = len(text)
print text
print length
raw_input('Enter to continue')
readMenu()
f.close()
elif choice == 'n':
readMenu()
def raw_lines(prompt=''):
result = []
getmore = True
while getmore:
line = raw_input(prompt)
if len(line) > 0:
result.append(line)
else:
getmore = False
result = str(result)
result.replace('[','').replace(']','')
return result
def mainMenu():
os.system("clear")
print Menu
choice = ''
choice = raw_input('--: ')
createLoop = True
if choice == '1':
return creationMenu()
elif choice == '2':
readMenu()
elif choice == '0':
os.system("clear")
sys.exit(0)
def create():
os.system("clear")
name = raw_input("Enter the file name: ")
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
while os.path.exists(dire):
os.system("clear")
print("This snippet already exists")
name = raw_input("Enter a different name: ")
dire = ('shelf/'+name+'.txt')
print("File created\n")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
else:
print("File created")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
print text
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
def readMenu():
os.system("clear")
name = ''
dire = ''
print ReadMenu
choice = raw_input('--:')
if choice == '1':
os.system("clear")
name = raw_input ('Enter Snippet name: ')
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
choice = ''
choice = raw_input('The Snippet exists! Open? (y/n)')
'''if not choice == 'y' or 'n':
while (choice != 'y') or (choice != 'n'):
choice = raw_input('Enter \'y\' or \'n\' to continue: ')
if choice == 'y' or 'n':
break'''
readFileLoop(choice, dire)
else:
raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back
readMenu()
elif choice == '0':
os.system("clear")
print Menu
def creationMenu(): ###### Menu to create, edit and delete a snippet ######
os.system("clear")
print CreateMenu
choice = raw_input('--: ')
if choice == '1': ### Create a snippet
os.system("clear")
print create()
print creationMenu()
elif choice == '2':
os.system("clear") ### Edit a snippet
print ("teh editon staton")
raw_input()
print creationMenu()
elif choice == '3':
os.system("clear") ### Delete a snippet
print ("Deletion staton")
raw_input()
print creationMenu()
elif choice == '0': ### Go Back
os.system("clear")
######## Main loop #######
running = True
print ('Welcome to the code library, please don\'t disturb other readers!\n\n')
while running:
mainMenu()
######## Main loop #######
鉈;博士:需要寫和讀多行文本文件
據我所知,你的代碼已經_does_讀取多行文本文件。 'f.read()'將整個文件讀入一個大字符串,充滿嵌入的換行符。我不明白爲什麼代碼的結構是這樣的,或者你爲什麼關閉文件兩次,或者其他各種各樣的事情,但是......究竟是什麼部分在這裏被破壞或丟失? – abarnert 2013-05-03 22:26:51
另外:「我曾經想過,我只能從文本文件中讀取它,並將每行添加到列表中,然後使用while循環單獨打印每行,但不幸的是這種行不起作用。」這有點含糊,但聽起來像是應該起作用的東西。沒有看到你嘗試過的實際代碼,很難告訴你這個想法或實現有什麼問題。 – abarnert 2013-05-03 22:28:00
@abarnert我遇到的問題是多行被存儲到文件的方式,它以列表格式存儲,例如['line1','line2','line3'],這使得難以閱讀多行因爲我無法將它作爲列表讀取,當我嘗試將所有存儲的字符串添加到一個列表項中時。我不知道我是否正確寫入文件。 – user2348424 2013-05-04 09:48:06