Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(简单Python)用户名的CSV输入_Python_String_Csv - Fatal编程技术网

(简单Python)用户名的CSV输入

(简单Python)用户名的CSV输入,python,string,csv,Python,String,Csv,我有一个CSV文件names.CSV First_name, Last_name Mike, Hughes James, Tango , Stoke Jack, ....etc 我想要的是能够将first\u name的第一个字母和完整的Last\u name作为用户名输出到屏幕上,但不包括first\u name和Last\u name属性为空的人。我完全被卡住了。任何帮助都将不胜感激 import csv ifile = open('names.csv', "rb") reader

我有一个CSV文件
names.CSV

First_name, Last_name
Mike, Hughes
James, Tango
, Stoke
Jack,
 ....etc
我想要的是能够将
first\u name
的第一个字母和完整的
Last\u name
作为用户名输出到屏幕上,但不包括
first\u name
Last\u name
属性为空的人。我完全被卡住了。任何帮助都将不胜感激

import csv 
ifile = open('names.csv', "rb") 
reader = csv.reader(ifile) 
rownum = 0 
for row in reader: 
    if rownum == 0: 
        header = row 
    else: 
        colnum = 0 
for col in row: 
    print '%-8s: %s' % (header[colnum], col) 
    colnum += 1 
    rownum += 1 
ifile.close()
尝试#2

我没有保存很多尝试,因为它们都不起作用:S

import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile, delimiter=',', quoting=csv.QUOTE_NONE)

for row in reader: 
    if not row[0] or not row[1]:
        continue
    print (row[0][0] + row[1]).lower()


从.csv获取文本后,可以使用split()函数将文本按新行分隔。您的示例文本有点不一致,但如果我正确理解您的问题,您可以说

import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile)
reader = reader.split('\n')
for x in reader
    print(reader[x])
或者,如果要用逗号分隔,只需将“\n”替换为“,”

可能是这样

from csv import DictReader

with open('names.csv') as f:
    dw = DictReader(f, skipinitialspace=True)

    fullnames = filter(lambda n: n['First_name'] and n['Last_name'], dw)
    for f in fullnames:
        print('{}{}'.format(f['First_name'][0], f['Last_name']))

您的csv中有标题,因此请使用
DictReader
,只需过滤掉那些名字或姓氏为空的标题,并显示其余的名称

你不应该自己试一试吗?对不起,csv文件条目应该是一行两行的我在过去的5个小时里一直没睡,正如我所说的,我会很感激你的帮助不要在评论中发布代码,编辑你的问题以包含你的代码(粘贴它,突出显示它,然后按Ctrl-K将其格式化为代码)。
import csv
dataFile = open('names.csv','rb')
reader = csv.reader(dataFile)
reader = reader.split('\n')
for x in reader
    print(reader[x])
from csv import DictReader

with open('names.csv') as f:
    dw = DictReader(f, skipinitialspace=True)

    fullnames = filter(lambda n: n['First_name'] and n['Last_name'], dw)
    for f in fullnames:
        print('{}{}'.format(f['First_name'][0], f['Last_name']))