简体   繁体   English

将数据附加到python中的文件末尾

[英]Append data to the end of a file in python

I am trying to append data to a file. 我试图将数据附加到文件。 Each line gets written inside a function. 每行都写在函数内。 Below is a sample code based on my actual code: 以下是基于我的实际代码的示例代码:

a = 0

def data():
    global a
    a = int(raw_input('Enter value for a\n>'))
    write()

def write():
    f = open('path\\to\\file.txt', "a")
    f.write('%s\n' % a)
    f.close
    proceed()

def proceed():
    should = raw_input('Please press enter to continue or type in 0 to stop\n>')
    if should == '0':
        return
    else:
        data()

data()

When I run the code and give, for example, 1, 2 and 3 as values for a, this is how it gets written to the file: 当我运行代码并给出例如1, 2 and 3作为a的值时,这就是它写入文件的方式:

3
2
1

But I want it to be written to the file this way: 但是我希望它以这种方式写入文件:

1
2
3

What would be the right way to do that? 这样做的正确方法是什么? How do I append a new line at the end of a file every time I run the write function? 每次运行write函数时,如何在文件末尾添加新行?

Your program structure gives rise to a possibly very deep recursion (problem). 您的程序结构可能会导致非常深的递归(问题)。 Because in data(), you call write(), and in write() you call proceed(), and in proceed() you call data() again. 因为在data()中,你调用write(),在write()中调用proceed(),在proceed()中再次调用data()。 Try to avoid this kind of structure. 尽量避免这种结构。 The following code avoids this problem, and is shorter: 以下代码可以避免此问题,并且更短:

def data():
    while True:
        a = int(raw_input('Enter value for a\n>'))
        f.write(str(a) + '\n')

        should = raw_input('Please press enter to continue or type in 0 to stop\n>')
        if should == 0:
            break


f = open('path\\to\\file.txt', "a")
data()
f.close()

The proper way to implement your demands has been given by @Ukimiku. @Ukimiku提供了实现您需求的正确方法。 As for why your code behaves like that, my opinion is here. 至于为什么你的代码表现如此,我的意见就在这里。 In fact, open a file with open('path','a') will move the file pointer to the end of the file you open so that when you use write() , you append something. 实际上,打开一个带有open('path','a')的文件会将文件指针移动到你打开的文件的末尾,这样当你使用write() ,你会追加一些东西。

f = open('path\\to\\file.txt', "a")
print f.tell() #get the position of current file pointer
f.write('%s\n' % a)

Add print f.tell() after you open file.txt. 打开file.txt后添加print f.tell() You will find every time you open it, the pointer position is always 0, which indicates that your write() operation insert those numbers at the beginning of that file. 每次打开它时都会发现,指针位置始终为0,这表示write()操作会在该文件的开头插入这些数字。 This happened because of no closing. 这是因为没有关闭。 Those changes happen in memory and haven't been written to disk yet. 这些更改发生在内存中,尚未写入磁盘。

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

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