简体   繁体   English

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

[英]Writing multiple lines to file and then reading them with Python

I've just undertaken my first proper project with Python, a code snippet storing program. 我刚刚使用Python(一个代码段存储程序)进行了第一个适当的项目。 To do this I need to first write, then read, multiple lines to a .txt file. 为此,我需要先向.txt文件写入多行,然后再读取。 I've done quite a bit of googling and found a few things about writing to the file (which didn't really work). 我做了很多的谷歌搜索工作,并发现了一些有关写入文件的事情(这实际上没有用)。 What I have currently got working is a function that reads each line of a multiline input and writes it into a list before writing it into a file. 我目前正在使用的功能是先读取多行输入的每一行,然后将其写入列表,然后再将其写入文件。 I had thought that I would just be able to read that from the text file and add each line into a list then print each line separately using a while loop, which unfortunately didn't work. 我以为我只能从文本文件中读取该行并将每行添加到列表中,然后使用while循环分别打印每行,但是不幸的是,这行不通。 After going and doing more research I decided to ask here. 经过研究后,我决定在这里询问。 This is the code I have currently: 这是我目前拥有的代码:

'''
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: Need to write and read multiline text files Tl; Dr:需要读写多行文本文件

The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format eg ['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. 我遇到的问题是将多行存储到文件的方式,它以列表格式存储,例如['line1', 'line2', 'line3'] ,这使得很难将其读为多行,因为我可以当我尝试将其存储为一个列表项时,就无法将其作为列表读取。 I don't know if I'm writing to the file correctly. 我不知道我是否正确写入文件。

OK, so the problem is with writing the file. 好的,所以问题出在文件上。 You're reading it in correctly, it just doesn't have the data you want. 您正在正确阅读它,只是它没有您想要的数据。 And the problem is in your raw_lines function. 问题出在您的raw_lines函数中。 First it assembles a list of lines in the result variable, which is good. 首先,它在result变量中汇编行列表,这很好。 Then it does this: 然后它这样做:

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

There are two small problems and one big one here. 这里有两个小问题,一个大问题。

First, replace : 首先, replace

Return[s] a copy of the string with all occurrences of substring old replaced by new . 返回字符串的副本,该字符串的所有出现的子字符串old都new替换。

Python strings are immutable. Python字符串是不可变的。 None of their methods change them in-place; 他们的方法都没有就地改变它们。 all of them return a new string instead. 它们都返回一个新字符串。 You're not doing anything with that new string, so that line has no effect. 您不会对该新字符串执行任何操作,因此该行无效。

Second, if you want to join a sequence of strings into a string, you don't do that by calling str on the sequence and then trying to parse it. 其次,如果要将字符串序列连接到字符串中,则不必通过在序列上调用str然后尝试对其进行解析来做到这一点。 That's what the join method is for. 这就是join方法的目的。 For example, if your lines already end with newlines, you want ''.join(result) . 例如,如果您的行已经以换行符结尾,则需要''.join(result) If not, you want something like '\\n'.join(result) + '\\n' . 如果不是,则需要类似'\\n'.join(result) + '\\n' What you're doing has all kinds of problems—you forgot to remove the extra commas, you will remove any brackets (or commas, once you fix that) within the strings themselves, etc. 您正在做的事情有各种各样的问题-您忘记删除多余的逗号,您将删除字符串本身内的所有方括号(或逗号,一旦您将其修复),等等。

Finally, you shouldn't be doing this in the first place. 最后,您不应该首先这样做。 You want to return something that can be passed to writelines , which: 您想要返回可以传递给writelines ,该行为包括:

Write[s] a sequence of strings to the file. 将一个字符串序列写入文件。 The sequence can be any iterable object producing strings, typically a list of strings. 该序列可以是产生字符串的任何可迭代对象,通常是字符串列表。

You have a list of strings, which is exactly what writelines wants. 您有一个字符串列表,这正是writelines想要的。 Don't try to join them up into one string. 不要试图将它们连接成一个字符串。 If you do, it will run, but it won't do the right thing (because a string is, itself, a sequence of 1-character strings). 如果这样做,它将运行,但不会做正确的事情(因为字符串本身就是一个1字符字符串的序列)。

So, if you just remove those two lines entirely, your code will almost work. 因此,如果您只完全删除这两行,您的代码几乎可以正常工作。

But there's one last problem: raw_input : 但是还有最后一个问题: raw_input

… reads a line from input, converts it to a string (stripping a trailing newline), and returns that. …从输入中读取一行,将其转换为字符串(带末尾的换行符),然后将其返回。

But writelines : 但是writelines

… does not add line separators. …不添加行分隔符。

So, you'll end up with all of your lines concatenated together. 因此,您最终将所有行连接在一起。 You need the newlines, but raw_input throws them away. 您需要换行符,但raw_input它们丢弃。 So, you have to add them back on. 因此,您必须重新添加它们。 You can fix this with a simple one-line change: 您可以通过简单的单行更改来解决此问题:

result.append(line + '\n')

To read multiple lines from a file, it's easiest to use readlines() , which will return a list of all lines in the file. 要从文件中读取多行,最简单的方法是使用readlines() ,它将返回文件中所有行的列表。 To read the file use: 要读取文件,请使用:

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

And to write out your changes, use: 并写下您的更改,请使用:

with open(directory, 'w') as f:
    f.writelines(lines)
fileList = [line for line in open("file.txt")]

While the previously mention idiom will work for reading files, I like mine. 尽管前面提到的习惯用法可以读取文件,但我还是喜欢我的。 Its short and to the point. 它的简短点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM