将多行写入文件,然后使用Python读取

2024-04-23 20:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚用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:需要写入和读取多行文本文件


Tags: ortotextnameinputrawifos
3条回答
fileList = [line for line in open("file.txt")]

虽然前面提到的习语可以用来阅读文件,但我喜欢我的。它简短而切题。

The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format e.g ['line1', 'line2', 'line3'] which is making it difficult to read as multilines because I can't get it to be read as a list, when I tried it added the whole stored string into one list item. I don't know if I'm writing to the file correctly.

好的,问题在于写入文件。你读得对,只是没有你想要的数据。问题出在raw_lines函数中。首先,它在result变量中组装一个行列表,这很好。然后它会这样做:

result = str(result)
result.replace('[','').replace(']','')

这里有两个小问题和一个大问题。

首先,^{}

Return[s] a copy of the string with all occurrences of substring old replaced by new.

Python字符串是不可变的。它们的任何方法都不会就地更改它们;而是返回一个新字符串。你不能用那条新的线做任何事,所以那条线没有效果。

第二,如果你想把一个字符串序列连接到一个字符串中,你不需要调用序列上的str,然后尝试解析它。这就是^{}方法的作用。例如,如果您的行已经以换行结束,则需要''.join(result)。如果不是,你需要像'\n'.join(result) + '\n'这样的东西。你正在做的事情有各种各样的问题,你忘记删除额外的逗号,你将删除字符串本身的任何括号(或逗号,一旦你修复了它),等等

最后,你不应该一开始就这么做。您希望返回可传递给^{}的内容,该内容:

Write[s] a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.

你有一个字符串列表,这正是writelines想要的。别想把它们串成一串。如果这样做,它将运行,但它不会做正确的事情(因为字符串本身是一个由1个字符组成的字符串序列)。

所以,如果您完全删除这两行代码,您的代码几乎就可以工作了。

但还有最后一个问题:^{}

… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

但是^{}

… does not add line separators.

所以,最后所有的行都连接在一起。你需要换行符,但是raw_input把它们扔掉了。所以,你必须把它们加回去。您可以通过简单的单行更改来解决此问题:

result.append(line + '\n')

要从文件中读取多行,最容易使用readlines(),它将返回文件中所有行的列表。要读取文件,请使用:

with open(directory, 'r') as f:
    lines = f.readlines()

要写出您的更改,请使用:

with open(directory, 'w') as f:
    f.writelines(lines)

相关问题 更多 >