在Python上使用CSV文件打开功能

时间:2013-05-20 02:20:33

标签: python fopen fwrite

好的,我想要做的是将内容写入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()函数不起作用。

我做错了吗?你能帮帮我吗?感谢。

3 个答案:

答案 0 :(得分: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())

答案 1 :(得分: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'])

资源: "using csv module"

答案 2 :(得分: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

~$