简体   繁体   English

如何在python 3.6中编辑多行文本文件?

[英]How to edit multiple-line text file in python 3.6?

I'm new to coding (cumulative 2 weeks of learning). 我是编码的新手(累计学习2周)。 I'm using python 3.6. 我正在使用python 3.6。 Currently I'm trying to read a file with text (copy.txt), edit it and write in another file (paste.txt). 目前,我正在尝试读取包含文本(copy.txt)的文件,对其进行编辑并写入另一个文件(paste.txt)。

Copy.txt looks like this: Copy.txt看起来像这样:

  ;ROLE_NAME                                                     ;GRANTOR  
1 ;rolea                                                         ;SYS      
2 ;rolec                                                         ;SYSTEM   
3 ;roley                                                         ;_SYS_REPO
4 ;rolez                                                         ;_SYS_REPO

And I want the text to look like this in paste.txt (after formatting): 我希望文本在paste.txt中看起来像这样(格式化后):

SYS
grant rolea to user

SYSTEM
grant rolec to user

_SYS_REPO
grant roley to user
grant rolez to user

What I've done by now - reading the file copy.txt, which is in the same dir as the script: 我现在所做的是-读取文件copy.txt,该文件与脚本位于同一目录中:

from os.path import abspath, exists

f_path = abspath("copy.txt")


if exists(f_path):
        with open(f_path) as f:
        print (f.read())

I don't have an idea how to make changes in each line. 我不知道如何在每一行中进行更改。 I was thinking about making a dictionary that takes two values and using f.split(';') to assign these values. 我正在考虑制作一个具有两个值的字典,并使用f.split(';')分配这些值。 Also I tought about counting the number of lines, and edit each one in loop, using this: 我也很想计算行数,并使用此方法循环编辑每一行:

num_lines = sum(1 for line in f)

Could you give me some guidelines about the concept how the text should be formatted? 您能给我一些有关如何格式化文本的概念的指导吗?

Disclaimer: I've read a lot of other posts, but couldn't find one helping me with my task. 免责声明:我已经阅读了很多其他文章,但是找不到帮助我完成任务的文章。

You're on the right track about thinking of creating a dictionary. 您正在思考如何创建字典。 You could create a dictionary that maps grantors to a list of roles . 你可以创建一个映射的字典grantors以列表roles

First, you need to read in the file, exactly like you have already done: 首先,您需要像完全一样读入文件:

from os.path import abspath, exists

f_path = abspath("copy.txt")

if exists(f_path):
    with open(f_path) as f:
        lines = f.readlines()

lines is just a list of the lines in "copy.txt" lines只是"copy.txt"的列表

Then you need to create that dictionary: 然后,您需要创建该字典:

role_dict = {}
for line in lines[1:]:
    split_line = line.split(';')
    role = split_line[1].strip()
    grantor = split_line[2].strip()
    if grantor in role_dict:
        role_dict[grantor].append(role)
    else:
        role_dict[grantor] = [role]

In the example you have given, role_dict would look like the following: 在您给出的示例中, role_dict如下所示:

{'SYS': ['rolea'], 'SYSTEM': ['rolec'], '_SYS_REPO': ['roley', 'rolez']}

Finally, you just need to write it out in order: 最后,您只需要按顺序写出:

with open('paste.txt', 'w') as f:
    for grantor in sorted(role_dict.keys()):
        roles = role_dict[grantor]
        f.write(grantor + '\n')
        for role in roles:
            f.write('grant {} to user\n'.format(role))
        f.write('\n')

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

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