我刚刚用Python(一个存储代码片段的程序)完成了第一个正确的项目。 要做到这一点,我需要先写,然后读,多行到一个.txt文件。我在谷歌上搜索了很多东西,找到了一些关于写文件的东西(这些东西并没有真正起作用)。我目前正在工作的是一个函数,它读取多行输入的每一行,并在将其写入文件之前将其写入列表。我本以为我可以从文本文件中读取它,然后将每一行添加到一个列表中,然后使用while循环分别打印每一行,但不幸的是,这个循环不起作用。 在做了更多的研究之后,我决定问这里。这是我目前拥有的代码:
'''
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 #######
Tl;Dr:需要写入和读取多行文本文件
虽然前面提到的习语可以用来阅读文件,但我喜欢我的。它简短而切题。
好的,问题在于写入文件。你读得对,只是没有你想要的数据。问题出在
raw_lines
函数中。首先,它在result
变量中组装一个行列表,这很好。然后它会这样做:这里有两个小问题和一个大问题。
首先,^{} :
Python字符串是不可变的。它们的任何方法都不会就地更改它们;而是返回一个新字符串。你不能用那条新的线做任何事,所以那条线没有效果。
第二,如果你想把一个字符串序列连接到一个字符串中,你不需要调用序列上的} 方法的作用。例如,如果您的行已经以换行结束,则需要
str
,然后尝试解析它。这就是^{''.join(result)
。如果不是,你需要像'\n'.join(result) + '\n'
这样的东西。你正在做的事情有各种各样的问题,你忘记删除额外的逗号,你将删除字符串本身的任何括号(或逗号,一旦你修复了它),等等最后,你不应该一开始就这么做。您希望返回可传递给^{} 的内容,该内容:
你有一个字符串列表,这正是
writelines
想要的。别想把它们串成一串。如果这样做,它将运行,但它不会做正确的事情(因为字符串本身是一个由1个字符组成的字符串序列)。所以,如果您完全删除这两行代码,您的代码几乎就可以工作了。
但还有最后一个问题:^{} :
但是^{} :
所以,最后所有的行都连接在一起。你需要换行符,但是
raw_input
把它们扔掉了。所以,你必须把它们加回去。您可以通过简单的单行更改来解决此问题:要从文件中读取多行,最容易使用
readlines()
,它将返回文件中所有行的列表。要读取文件,请使用:要写出您的更改,请使用:
相关问题 更多 >
编程相关推荐