1

好的,我想做的是将一些内容写入 CSV 文件。我正在这样做:

directory = open('docs/directory.csv', 'a+', encoding='utf-8')
name = input('Please insert a name: ')
phone = input('Please insert a phone number: ')

directory.write(name + ',' + phone + ',\n')

print(directory.read())

'a+'习惯在文件末尾附加每一行。这里一切正常,每次我运行脚本时都会将数据添加到文件的末尾,但问题是最后没有显示数据,显然,该read()功能不起作用。

难道我做错了什么?你能帮我解决这个问题吗?谢谢。

4

3 回答 3

1

当您调用 时read,您从文件指针的当前位置读取到文件末尾。但是,您已经在文件末尾有了文件指针,因此没有返回任何内容。

在这种情况下,我会以'rw+'模式打开文件,寻找到最后,然后追加内容。

directory = open('docs/directory.csv', 'a+', encoding='utf-8')
directory.seek(0,2) #seek to the end

name = input('Please insert a name: ')
phone = input('Please insert a phone number: ')

directory.write(name + ',' + phone + ',\n')

directory.seek(0) #seek back to beginning
print(directory.read())
于 2013-05-20T02:22:57.020 回答
0

Python 有一个标准库,称为csv

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

资源: “使用 csv 模块”

于 2013-05-20T02:23:36.963 回答
0

尝试这个:

~$ cat test.py
name = raw_input('Please insert a name: ')
phone = raw_input('Please insert a phone number: ')

# Opening in a+ mode will point the file pointer to the end of the file.
# We will fix this with seek().
directory = open('test.csv', 'a+')

# Seek to the 0th offset from the end of the file (option 2).
directory.seek(0, 2)

# Write the data at the end of the file.
directory.write(name + ',' + phone + '\n')

# Seek to the beginning of the file (option 0).
directory.seek(0, 0)

# Read the file and print output.
print(directory.read())
~$ >test.csv
~$ python test.py
Please insert a name: Test Name 1
Please insert a phone number: 111-222-3344
Test Name 1,111-222-3344

~$ python test.py
Please insert a name: Test Name 2
Please insert a phone number: 222-333-4444
Test Name 1,111-222-3344
Test Name 2,222-333-4444

~$ 
于 2013-05-20T02:37:33.930 回答