从一个文本文件中读取,解析它,然后将它转换成一个cs

2024-10-01 11:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含用户信息的文本文件。我想解析数据,所以我只有用户名,然后我想用解析的数据创建一个csv文件。你知道吗

这是文本文件,我的脚本正在读取。你知道吗

blah.com\user1:dajlfnadjhlasdjasnasjlfn:test1
blah.com\user2:dajlfnadjhlasdjasnasjlfn:test2
blah.com\user3:dajlfnadjhlasdjasnasjlfn:test3
blah.com\user4:dajlfnadjhlasdjasnasjlfn:test4
blah.com\user5:dajlfnadjhlasdjasnasjlfn:test5
blah.com\user6:dajlfnadjhlasdjasnasjlfn:test6

这是我的剧本

import time, os, os.path, sys, string, datetime, time, shutil, csv

#Locate the file

globalpath = 'C:\\users\\userinfo\\'

todaysdatefull = datetime.datetime.now()
todaysdate = todaysdatefull.strftime("%Y-%m-%d")

datapath = globalpath + 'data\\' + todaysdate + "\\"
logfile = datapath + 'userinfo.txt'
potfile = datapath + 'parsed.csv' 

infile = logfile
outfile = potfile
lines = []

# Open the file, find the username and parses it

with open(infile, 'r') as f:
        for line in f:
                usernamestart = line.find('\\')
                usernameend = line.find(':')
                username = line[usernamestart+1:usernameend]
                lines.append(username)
print(username)


# Outputs the data as a csv file

with open(outfile, 'w') as csv:
        writer = csv.writer(csv)
        for i in range(len(lines)):
                 writer.writerow(('Username', 'Date'))
                 writer.writerow(lines[i])

结果:

Traceback (most recent call last):
  File "C:\Automation\autocrack\highrisk_parser.py", line 33, in <module>
    writer = csv.writer(csv)
AttributeError: 'file' object has no attribute 'writer'

Tags: csvtheincomdatetimeaslineusername
1条回答
网友
1楼 · 发布于 2024-10-01 11:27:55

它来自这条线 with open(outfile, 'w') as csv:,您正在覆盖csv导入。你应该重命名你这样写的文件

with open(outfile, 'w') as csv_to_write:
    writer = csv.writer(csv_to_write)
    # Write the header once.
    writer.writerow(tuple(['Username', 'Date']))
    for one_line in lines:
        # you have to give the function a tuple, if not, the writerow iterates on each element of the string for writing it in a new line.
        writer.writerow(tuple([one_line, '']))

查找用户名的第一部分代码可以按以下步骤进行:

with open(infile, 'r') as f:
    lines = [line.split('\\')[-1].split(':')[0] for line in f]

相关问题 更多 >