简体   繁体   English

将字典写入 Python 中的文本文件 3

[英]Writing a Dictionary to a text file in Python 3

This is my first post so please forgive me if there are errors/misunderstandings.这是我的第一篇文章,如果有错误/误解,请原谅我。 I'm very new to python and trying to use it to improve and automate my everyday job as an IT technician.我对 python 非常陌生,并试图用它来改进和自动化我作为 IT 技术人员的日常工作。

My problem:我的问题:

I have 15000+.txt files that have a four-digit number in each file (or not) that I'm using RegEx to retrieve, store in a dictionary, and print.我有 15000+.txt 文件,每个文件(或没有)中都有一个四位数字,我使用 RegEx 检索、存储在字典中和打印。 This works well and fine for me!这对我来说很好用! (code for this below) (下面的代码)

import re, os
from os import listdir

txtfiles = [f for f in listdir("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\")]

txtlist = {}


for file in txtfiles:
    with open("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\" + file) as filename:
        for line in filename:
            if re.search('\(\w+\/3\d+@', line):
                entry = re.search('\/(\d+)', line).group(1)
                if entry in txtlist:
                    txtlist[entry] += 1
                else:
                    txtlist[entry] = 1

for key, value in txtlist.items():
    print(key, " : ", value)

This prints:这打印:

3008  :  36
3007  :  64
3015  :  68
3004  :  66
3017  :  32

Which is exactly what I want, yay me.这正是我想要的,是的。

I'm now trying to get this to create a file in the same folder as all the other textfiles that will have the same formatting as the print call.我现在正试图让它在与所有其他文本文件相同的文件夹中创建一个文件,这些文本文件将具有与打印调用相同的格式。 Unfortunately, I'm getting the error:不幸的是,我收到了错误:

Traceback (most recent call last):
  File "C:/Users/filepathofpycharmpytonfile", line 25, in <module>
    file.write(key, ' : ', value)
TypeError: write() takes exactly one argument (3 given)

Here is my code for the above error:这是我针对上述错误的代码:

import re, os
from os import listdir

txtfiles = [f for f in listdir("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\")]

txtlist = {}


for file in txtfiles:
    with open("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\" + file) as filename:
        for line in filename:
            if re.search('\(\w+\/3\d+@', line):
                entry = re.search('\/(\d+)', line).group(1)
                if entry in txtlist:
                    txtlist[entry] += 1
                else:
                    txtlist[entry] = 1


with open("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\"1.Results.txt", "x" ) as file:
    for key, value in txtlist.items():
        file.write(key, ' : ', value)

So, my question is, how do I write the results to a file in the same way that I printed them to my console?所以,我的问题是,如何以与将结果打印到控制台相同的方式将结果写入文件?

Thanks in advance!提前致谢!

PS To get around this, I wrote it as a JSON file which worked but obviously didn't keep the formatting I wanted. PS 为了解决这个问题,我将其编写为 JSON 文件,该文件有效,但显然没有保持我想要的格式。 Please see code below:请看下面的代码:

import re, os
import json
from os import listdir

txtfiles = [f for f in listdir("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\")]

txtlist = {}


for file in txtfiles:
    with open("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\" + file) as filename:
        for line in filename:
            if re.search('\(\w+\/3\d+@', line):
                entry = re.search('\/(\d+)', line).group(1)
                if entry in txtlist:
                    txtlist[entry] += 1
                else:
                    txtlist[entry] = 1


with open("C:\\Users\\Redacted\\Redacted\\Redacted\\Redacted\\1.Results.txt", "x" ) as file:
    file.write(json.dumps(txtlist))

Try formatting what you want to write with an f-string:尝试用 f 字符串格式化你想写的内容:

file.write(f'{key} : {value}\n')

instead of file.write(key, ': ', value) try file.write(key + ': ' + value)而不是file.write(key, ': ', value)尝试file.write(key + ': ' + value)

Concatting the strings instead of passing multiple arguments, because as the error states file.write only expexts one argument.连接字符串而不是传递多个 arguments,因为错误状态 file.write 仅显示一个参数。

file.write only accepts a single string argument, but in your code file.write(key, ': ', value) , you are passing in three arguments. file.write只接受一个字符串参数,但在您的代码file.write(key, ': ', value)中,您传入了三个 arguments。 Change it, as the others mentioned, to a single string input.正如其他人提到的,将其更改为单个字符串输入。

Eg @mrblewog's answer例如@mrblewog 的回答

file.write(f'{key} : {value}')

You can check out this link for a simple explanation您可以查看此链接以获得简单的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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