簡體   English   中英

從文本文件中讀取,解析它,然后將其轉換為csv

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

我有這個包含用戶信息的文本文件。 我想解析數據,所以我只有用戶名,然后我想創建一個帶有解析數據的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'

它來自這行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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM