Python:使用CSV解析(?)变量,然后将其输出到另一个文件

埃萨贝尔

我是服务器管理员。我不必进行大量脚本编写,但是a脚-它抬起了丑陋的头。

摘要:我有example.csv,如下所示;

Stan,Marsh,Stan Marsh,1001,899,smarsh,[email protected]
Eric,Cartman,Eric Cartman,1002,898,ecartman,[email protected]

现在。我正在尝试读取csv文件。然后,我想从每一行中获取值并将其放入这样的内容中;

dn: cn=$CN,ou=People,dc=domain,dc=com
cn: $CN
gidnumber: 20
givenname $FN
homedirectory /home/users/$USER
loginshell: /bin/sh
objectclass: inetOrgPerson
objectclass: posixAccount
objectclass: top
sn: $LN
uid: $USERNAME
telephoneNumber: $TELE
uidnumber: $UIDN
userpassword: {CRYPT}mrpoo
mail: $EMAIL

如您所见,我正在尝试制作一个LDIF文件,该文件允许我导入用户名,然后自动填写变量。

我似乎无法拼凑而成。

我也没有走太远。我学会了打印行,是的...!

import csv

with open('example.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
                print row

我认为逻辑如下。

  • 导入.CSV。遍历行。
  • 将数据放入变量。
  • 将最终产品(打印?)输出到“ Output_File”中
  • 循环播放直到EOF?

任何帮助,将不胜感激。

AKX

像这样的东西应该工作。

CSV模块对于像您这样的文件来说是多余的。

我在这里使用的一些Python惯用法:

  • dict(zip(keys, values))-压缩键列表和值列表;dict功能(或dict.update)可以消化那些作为键-值对要添加到一个字典
  • 映射形式的字符串插值(%(foo)s)然后可以提取字典

defaults位在那里,因此字符串插值不会因丢失值而阻塞。适应您的需求。:)

if True:  # For testing -- use the other branch to read from a file
    # Declare some test content in a string...
    input_content = """
Stan,Marsh,Stan Marsh,1001,899,smarsh,[email protected]
Eric,Cartman,Eric Cartman,1002,898,ecartman,[email protected]
    """.strip()
    # And use the StringIO module to create a file-like object from it.
    from StringIO import StringIO
    input_file = StringIO(input_content)
else:
    # Or just open the file as normal. In a short script like this,
    # one doesn't need to worry about closing the file - that will happen
    # when the script ends.
    input_file = open('example.csv', 'rb')


# Declare the fields in the order they are in the file.
# zip() will use this later with the actual fields from the file
# to create a dict mapping.
fields = ('FN', 'LN', 'NAME', 'UIDN', 'GIDN', 'CN', 'EMAIL')  # Fields, in order

# Declare a template for the LDIF file. The %(...)s bits will be
# later interpolated with the dict mapping created for each input row.
template = u"""
dn: cn=%(CN)s,ou=People,dc=domain,dc=com
cn: %(CN)s
gidnumber: 20
givenname %(FN)s
homedirectory /home/users/%(USER)s
loginshell: /bin/sh
objectclass: inetOrgPerson
objectclass: posixAccount
objectclass: top
sn: %(LN)s
uid: %(USERNAME)s
telephoneNumber: %(TELE)s
uidnumber: %(UIDN)s
userpassword: {CRYPT}mrpoo
mail: %(EMAIL)s
"""

for line in input_file:
    # Create `vals` with some default values. These would be overwritten
    # if the CSV data (and of course the declared fields) contain them.
    vals = {"USER": "XXX", "TELE": "XXX", "USERNAME": "XXX"}

    # line.strip().split() will turn the string line,
    # for example 'foo,baz,bar\n' (trailing new line `strip`ped out)
    # into the list ['foo', 'baz', 'bar'].
    # zipping it with, say, ['LN', 'FN', 'EMAIL'] would yield
    # [('LN', 'foo'), ('FN', 'baz'), ('EMAIL', 'bar')] -- 
    # ie. a list of tuples with a key and a value.
    # This can be used by the `dict.update` function to replace and augment
    # the default values declared above.

    vals.update(zip(fields, line.strip().split(",")))

    # Finally, use the interpolation operator % to merge the template with the
    # values for this line and print it to standard output.

    print template % vals

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何运行另一个程序并将其仅输出到终端的特定部分

比较两个大的csv文件,然后用python编写另一个

如何从文件中读取每一行并将其输出到具有扩展名的另一个文件

使用Powershell从多个XML文件中的元素获取数据以输出到另一个单个XML文件

删除文件中每一行的前缀,并使用sed输出到另一个文件

如何返回ffmepg处理的输出文件并将其传递给另一个函数?使用python

在目录中的多个文件上执行python代码,并将多个文件输出到另一个目录

抓取特定行并将其导出到另一个csv

Python:尝试将行从一个csv文件提取并输出到另一个csv文件

如何在一个文件夹中合并多个.js文件并将其输出到另一个文件夹?

从csv文件读取特定的列,然后使用python写入另一个CSV

在树枝模板中设置变量,然后将其与另一个变量一起使用

从文件中提取所有以某些顺序开头的行,然后将其输出到另一个文件

计算变量,并将其输出到另一个变量

如何将FLV编码为一个临时文件,然后使用FFMpeg将其输出到stdout?

如何使用通配符过滤掉字符串,然后将其修改后输出到另一个文本文件中?

Makefile处理一个目录中的所有文件,然后输出到另一个目录。

在CSV文件中应用diff()函数,然后导出到另一个CSV文件

从另一个文件添加项目,然后使用数组列表将其存储在另一个文件中

Python从文件中提取数据并输出到另一个

使用一个awk输出到另一个awk命令

在一个表中查找值并使用 join/awk 将其输出到另一个表中

读取 .csv 的内容并使用 python 将其写入另一个 .csv 文件

区分两个大的 CSV 文件(每个 90GB)并输出到另一个 csv

搜索 java 文件中的行并使用批处理脚本输出到另一个文件

输入文件并输出到另一个文件并将流文件传递给函数

用另一个名称替换输出的一列并将其保存为 .CSV 文件

将变量从一个线程输出到另一个线程

使用Python从一个文件夹中读取excel文件并输出到另一个文件夹中的csv文件时收到PermissionError?