python将变量写入文件_用python将变量写入文件

这个示例展示了如何使用Python的csv模块将一个由空格分隔的数据文件转换为逗号分隔的CSV文件。通过定义一个自定义的`unix_space`方言,程序读取输入文件并将其内容写入CSV格式,保留原始数据结构。最终输出的CSV文件内容正确,列之间用逗号分隔,并且保持了原始数据的完整性。
摘要由CSDN通过智能技术生成

您可以使用带方言的csv模块来读写文件。如果不自己重写csv处理代码,则不太容易出错。在

要解决您的错误,请执行以下操作:csvfile.write(','.join(str) + '\n')

这是你的整个程序被重写为更具Python特征的程序。它不包括字段周围的引号,但您可以自己添加它们。但是,只需使用csv模块,让它为您做一切。在

^{pr2}$

下面是一个使用csv模块的完整示例:#!/usr/bin/env python3

import csv

def convert(space_separated_file, csv_file):

class unix_space(csv.unix_dialect):

def __init__(self):

self.delimiter = ' '

input_rows = csv.reader(space_separated_file, dialect=unix_space())

output = csv.writer(csv_file, dialect='unix')

output.writerows(input_rows)

def example(in_filename, out_filename):

with open(in_filename) as f_in:

with open(out_filename, "w") as f_out:

convert(f_in, f_out)

def test():

with open('test.txt', 'w') as f:

f.write('''"Number" "Date" "Time" "Interface" "Origin" "Type" "Action" "Service" "Source Port" "Source" "Destination" "Protocol" "Rule" "Rule Name" "Current Rule Number" "User" "Information" "Product" "Source Machine Name" "Source User Name"

"176" "16Oct2017" "23:59:00" "eth1" "FWSIN2" "Log" "Accept" "TCP_135" "62005" "Host_10.2.2.68" "10.168.150.135" "tcp" "271" "" "271-SINFW" "" "inzone: Internal; outzone: External; service_id: TCP_135" "Security Gateway/Management" "" ""

''')

example('test.txt', 'test.csv')

with open('test.csv') as f:

print(f.read())

test()

输出:"Number","Date","Time","Interface","Origin","Type","Action","Service","Source Port","Source","Destination","Protocol","Rule","Rule Name","Current Rule Number","User","Information","Product","Source Machine Name","Source User Name"

"176","16Oct2017","23:59:00","eth1","FWSIN2","Log","Accept","TCP_135","62005","Host_10.2.2.68","10.168.150.135","tcp","271","","271-SINFW","","inzone: Internal; outzone: External; service_id: TCP_135","Security Gateway/Management","",""

您的输出:Number,Date,Time,Interface,Origin,Type,Action,Service,Source Port,Source,Destination,Protocol,Rule,Rule Name,Current Rule Number,User,Information,Product,Source Machine Name,Source User Name

176,16Oct2017,23:59:00,eth1,FWSIN2,Log,Accept,TCP_135,62005,Host_10.2.2.68,10.168.150.135,tcp,271,,271-SINFW,,inzone: Internal; outzone: External; service_id: TCP_135,Security Gateway/Management,,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值