Python代码问题-尝试创建一个脚本来查找文件,对其进行编辑并将其保存为新文件

时间:2019-07-18 19:37:14

标签: python parsing

我正在尝试创建一个脚本来查找我的文本文件。找到我的文本文件后,它将解析文件中的数据,然后将该文件另存为新文件。

更具体地说,我有一个包含用户信息列表的文件,我希望我的脚本找到用户名,将其解压缩,然后将其另存为仅包含用户名的新文件。

infile = r"C:/Highrisk/userinfo.txt"
outfile = r"C:/Highrisk/parsed.txt"
lines = []

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


with open(outfile, 'w') as f:
    for i in range(len(lines)):
        f.write(lines[i])

执行此代码时,它只会删除原始文件中的所有文本。

3 个答案:

答案 0 :(得分:0)

使用open时,“ w”用于书写,“ r”用于读取。由于它无法读取文件,因此它仅遍历任何内容并将其解析为空文件。您将要授予它这样的读取权限:

infile = r"C:\test\userinfo.txt"
outfile = r"C:test\parsed.txt"
lines = []

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


with open(outfile, 'w') as f:
    for i in range(len(lines)):
        f.write(lines[i])

另外,您可能造成的另一个错误是您使用了以下行

usernamestart = line.find('\')

'\'字符是一个特殊字符,需要将其转义,如下所示:

usernamestart = line.find('\\')

此外,您需要在列表的第一个循环中存储信息,以便在写入其他文件时可以使用它。

答案 1 :(得分:0)

您需要在读取用户名的同一循环中将其写入文件,或将其保存在列表中,然后将其输出到文件中。

用于在同一循环中写入文件:

infile = r"C:\test\userinfo.txt"
outfile = r"C:test\parsed.txt"
lines = []

## open output file to write in
fout = open(outfile, 'w') 
## read input file
with open(infile, 'r') as f:
        for line in f:
            usernamestart = line.find('\\')
            usernameend = line.find(':')
            username = line[usernamestart+1:usernameend]
            ## writing in the output file
            fout.write(username+'\n')

fout.close()

答案 2 :(得分:0)

我设法使代码正常工作,非常感谢您的所有帮助。

# Opens the allcracked.txt file, parses it and stores it as a new file 

infile = r"C:\Highrisk\crackedtest.txt"
outfile = r"C:\Highrisk\parsed.txt"
lines = []

# Locates the file, looks for the username
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)

#Creates a new file with the usernames
with open(outfile, 'w') as f:
     for i in range(len(lines)):
         f.write(lines[i])
         f.write("\n")