简体   繁体   中英

Reading from a text file, parsing it, then converting it to a csv

I have this text file, that contains user information. I want to parse the data, so I only have the username, and then I want to create a csv file with that parsed data.

This is the text file, my script is reading from.

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

Here is my script

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])

Result:

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'

It is coming from this line with open(outfile, 'w') as csv: , your are overwriting the csv import. You should rename the file where you write like this

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, '']))

Your first part of code finding the username can be done as following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM