如何在没有\n的情况下使用python在文本文件中添加新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18065379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:50:28  来源:igfitidea点击:

how to add a new line in a text file using python without \n

pythonpython-3.x

提问by Suit Boy Apps

I have a file that has a list of files but it adds \nat the end how can I have python just write the info I need on a new line without getting \nin the way so that way my info will be called X.accnot x.acc\n? Here is my code that writes the file

我有一个具有文件列表的文件,但它增加了\n在最后我怎么能有蟒蛇只是写我需要一个新的行信息没有得到\n的方式,这样的方式我的信息将被称为X.accx.acc\n?这是我写文件的代码

def add(x):
    nl = "\n"
    acc = ".acc"
    xy = x + acc
    exyz = xy
    xyz = exyz
    xxx = str(xyz)
    tf = open('accounts.dat',"a+")
    tf.writelines(nl)
    tf.writelines(xxx)
    tf.close

Here is the code that calls upon the file:

这是调用文件的代码:

import sys

tf = open('accounts.dat','r')
names = tf.readlines()




u = choicebox(msg="pick something",title = "Choose an account",choices=(names))


counter_file = open(u, 'r+')
content_lines = []

for line in counter_file:
    if line == "credits =":
        creds = line
    else:
        False


for line in counter_file:
        if 'credits =' in line:
                line_components = line.split('=')
                int_value = int(line_components[1]) + 1
                line_components[1] = str(int_value)
                updated_line= "=".join(line_components)
                content_lines.append(updated_line)
        else:
                msgbox(msg=(creds))
                content_lines.append(line)

counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()

thank you for your help and sorry if this is a trival question still new to python :)

感谢您的帮助,如果这是一个对 python 来说仍然是新问题的琐碎问题,我深表歉意:)

采纳答案by Henry Keiter

Your question doesn't actually make sense, because of what a "line" actually is and what that '\n'character means.

您的问题实际上没有意义,因为“线”实际上是什么以及该'\n'字符的含义。

Files don't have an intrinsic concept of lines. A file is just a sequence of bytes. '\n'is the line separator (as Python represents it with universal newlines). If you want your data to show up on different "lines", you mustput a line separator between them. That's all that the '\n'character is. If you open up the file in a text editor after you write it, most editors won't explicitly show the newline character by default, because it's already represented by the separation of the lines.

文件没有线的内在概念。文件只是一个字节序列。'\n'是行分隔符(因为 Python 用通用换行符表示它)。如果您希望数据显示在不同的“行”上,则必须在它们之间放置一个行分隔符。这就是'\n'角色的全部内容。如果在编写文件后在文本编辑器中打开文件,默认情况下大多数编辑器不会显式显示换行符,因为它已经由行分隔表示。



To break down what your code is doing, let's look at the addmethod, and fix some things along the way.

为了分解您的代码正在做什么,让我们看看add方法,并在此过程中修复一些问题。

The first thing adddoes is name a variable called nland assign it the newline character. From this, I can surmise that nlstands for "newline", but it would be much better if that was actually the variable name.

首先要做的add是命名一个被调用的变量nl并为其分配换行符。由此,我可以推测它nl代表“换行符”,但如果它实际上是变量名会好得多。

Next, we name a variable called accand assign it the '.acc'suffix, presumably to be used as a file extension or something.

接下来,我们命名一个名为的变量acc并为其分配'.acc'后缀,大概是用作文件扩展名之类的。

Next, we make a variable called xyand assign it to x + acc. xyis now a string, though I have no idea of what it contains from the variable name. With some knowledge of what xis supposed to be or what these lines represent, perhaps I could rename xyto something more meaningful.

接下来,我们创建一个名为的变量xy并将其分配给x + accxy现在是一个字符串,虽然我不知道它从变量名中包含什么。有了一些关于x应该是什么或这些线代表什么的知识,也许我可以重命名xy为更有意义的东西。

The next three lines create three new variables called exyz, xyz, and xxx, and point them all to the same string that xyreferences. There is no reason for any of these lines whatsoever, since their values aren't really used in a meaningful way.

接下来的三行创建了三个名为exyzxyz和 的新变量xxx,并将它们都指向xy引用的同一个字符串。这些行中的任何一条都没有任何理由,因为它们的值并没有真正以有意义的方式使用。

Now, we open a file. Fine. Maybe tfstands for "the file"? "text file"? Again, renaming would make the code much more friendly.

现在,我们打开一个文件。美好的。也许tf代表“文件”?“文本文件”?同样,重命名将使代码更加友好。

Now, we call tf.writelines(nl). This writes the newline character('\n') to the file. Since the writelinesmethod is intended for writing a whole list of strings, not just a single character, it'll be cleaner if we change this call to tf.write(nl). I'd also change this to write the newline at the end, rather than the beginning, so the first time you write to the file it doesn't insert an empty line at the front.

现在,我们调用tf.writelines(nl). 这会将换行符( '\n')写入文件。由于该writelines方法旨在编写整个字符串列表,而不仅仅是单个字符,因此如果我们将此调用更改为tf.write(nl). 我也会改变它在末尾而不是开头写换行符,所以第一次写入文件时它不会在前面插入一个空行。

Next, we call writelinesagain, with our data variable (xxx, but hopefully this has been renamed!). What this actually does is break the iterable xxx(a string) into its component characters, and then write each of those to the file. Better replace this with tf.write(xxx)as well.

接下来,我们writelines再次调用,使用我们的数据变量 ( xxx,但希望它已被重命名!)。这实际上是将可迭代对象xxx(一个字符串)分解为其组成字符,然后将每个字符写入文件。最好也用这个代替tf.write(xxx)

Finally, we have tf.close, which is a reference to the closefunction of the file object. It's a no-op, because what you presumably meant was to close the file, by calling the method: tf.close(). We could also wrap the file upas a context manager, to make its use a little cleaner. Also, most of the variables aren't necessary: we can use string formattingto do most of the work in one step. All in all, your method could look like this at the end of the day:

最后,我们有tf.close,它是close对文件对象函数的引用。这是一个空操作,因为你大概的意思是关闭文件,通过调用方法:tf.close()。我们还可以将文件包装上下文管理器,以使其使用更简洁。此外,大多数变量不是必需的:我们可以使用字符串格式在一个步骤中完成大部分工作。总而言之,您的方法在一天结束时可能如下所示:

def add(x):
    with open('accounts.dat',"a+") as output_file:
        output_file.write('{0}.acc\n'.format(x))


So you can see, the reason the '\n'appears at the end of every line is because you are writing it between each line. Furthermore, this is exactly what you have to doif you want the lines to appear as "lines" in a text editor. Without the newline character, everything would appear all smashed together (take out the '\n'in my addmethod above and see for yourself!).

所以你可以看到,'\n'出现在每行末尾的原因是因为你在每行之间写了它。此外,如果您希望行在文本编辑器中显示为“行” ,这正是您必须做的。如果没有换行符,一切都会看起来都粉碎在一起(取出上面'\n'我的add方法中的,自己看看!)。



The problem you described in the comment is happening because namesis a direct reading of the file. Looking at the readlinesdocumentation, it returns a list of the lines in the file, breaking at each newline. So to clean those names up, you want line 4 of the code you posted to call str.stripon the individual lines. You can do that like this:

您在评论中描述的问题正在发生,因为names是直接读取文件。查看readlines文档,它返回文件中的行列表,在每个换行符处中断。因此,要清理这些名称,您需要发布的代码的第 4 行在str.strip各个行上调用。你可以这样做:

names = tf.readlines()
for i in range(len(names)):
    names[i] = names[i].strip() # remove all the outside whitespace, including \n

However, it's muchcleaner, quicker, and generally nicer to take advantage of Python's list comprehensions, and the fact that file objects are already iterable line-by-line. So the expression below is equivalent to the previous one, but it looks far nicer:

然而,利用 Python 的列表推导式以及文件对象已经可以逐行迭代这一事实,它简洁、更快捷,而且通常更好。所以下面的表达式等价于前一个,但看起来好得多:

names = [line.strip() for line in tf]

回答by Steve Barnes

Just change add:

只需更改添加:

def add(x):
    nl = "\n"
    acc = ".acc"
    xy = x + acc
    exyz = xy
    xyz = exyz
    xxx = str(xyz)
    tf = open('accounts.dat',"a+")
    tf.writelines(xxx)
    tf.writelines(nl)  # Write the newline AFTER instead of before the output
    tf.close()  # close is a function so needs to be called by having () at the end.

See the comments for what has changed.

请参阅评论以了解已更改的内容。

回答by sohom

why dont you just write a function with "\n" at the end of the line. So no need recall "\n" every time

为什么不在行尾写一个带有“\n”的函数。所以不需要每次都回忆“\n”

I did this way-

我是这样做的——

import os
log_path = r"c:\python27\Logs\log.txt"
if not os.path.exists(r"c:\python27\Logs"):
    os.mkdir(r"c:\python27\Logs")
def write_me_log(text):
    global log_path
    with open(log_path,"a+") as log:
        log.write(text+"\n")
write_me_log("Hello this is the first log text with new line")

回答by nathan

 file = open("accountfile.txt","a")
file.write(username)
file.write(" ")
file.write(password)
file.write(" ")
file.write(age)
#need it to go down a line here so it writes"hello world" on the next line
file.write("hello world")
file.close()``