简体   繁体   English

在python中对文本文件执行多次写入操作

[英]perform multiple write operations on a text file in python

I am trying to clean up a text file to a desired format.我正在尝试将文本文件清理为所需的格式。 To achieve this i am currently opening the file, performing a certain operation and closing it.I am repeating the same for few other operations.为了实现这一点,我目前正在打开文件,执行某个操作并关闭它。我对其他一些操作重复相同的操作。 Is there a better way of doing this.有没有更好的方法来做到这一点。 The operations that i want to perform are我要执行的操作是

  1. Open the text file and replace a certain string with a new string打开文本文件并用新字符串替换某个字符串
  2. Delete all the above string upto the new strings删除所有上述字符串直到新字符串
  3. Remove any tabs in the text file删除文本文件中的任何选项卡
  4. Replace all blank spaces with a comma用逗号替换所有空格

Furthermore,i am writing the output to a new file every time.此外,我每次都将输出写入一个新文件。 Can i do all these in the same file while all performing the formatting operations?我可以在执行格式化操作的同时在同一个文件中执行所有这些操作吗?

Text file sample文本文件示例

ANX ANV 91 BB
cc yy the 12
okr out 1 11 


temp1   temp2(a/b)      temp3(t)  temp4(x)
0   11  9a   1.1
1   22  9b   12
2   33  9c   4
3   44  9d   92

Expected:预期的:

temp1,temp2,temp3,temp4
0,11,9a,1.1
1,22,9b,12
2,33,9c,4
3,44,9d,92

My code我的代码

OldString = "temp1   temp2(a/b)      temp3(t)  temp4(x)"
NewString = "temp1 temp2 temp3 temp4"


def myfunction():    
    inputFile = open("Temp1.txt",encoding="utf8")
    exportFile = open('File1.txt','w',encoding="utf8")

    with inputFile as f:
        #Repalce old string by NewString
        newText=f.read().replace(OldString,NewString)
    
    with exportFile as f:
        f.write(newText)
        
    lines_to_write = []
    tag_found = False
 
    #Delete all extra strings upto the NewString.
    #Also remove any tabs
    with open('File1.txt',encoding="utf8") as in_file:
        for line in in_file:
            if line.strip() == NewString:
                tag_found = True
            if tag_found:
                lines_to_write.append(line.replace('\t', ' '))

    with open('File2.txt','w',encoding="utf8") as out_file:
        out_file.writelines(lines_to_write)

    lines_to_write = []
    tag_found = False

    #Replace all blank spaces with comma
    with open('File2.txt',encoding="utf8") as in_file:
        for line in in_file:
            if line.strip() == NewString:
                tag_found = True
            if tag_found:
                lines_to_write.append(line.replace(' ', ','))
        
        with open('File3.txt','w',encoding="utf8") as out_file:
            out_file.writelines(lines_to_write)

Thank you谢谢

I've wrote a little function to do what you want.我写了一个小函数来做你想做的事。 It starts by looking the first line you want to append in the new file.它首先查看您要添加到新文件中的第一行。 Then it format and append to an array only the lines coming after this one.然后它格式化并仅将后面的行附加到数组中。 Then it create a file writing this new array.然后它创建一个写入这个新数组的文件。

# Get index of first string to insert
def get_index(file, string):
    for line in file:
        if string in line:
            return file.index(line)


# Main function to write files
def write_files(in_file, out_file, old_string, new_string):

    # Opens input file, loads to a list then close
    with open(in_file, 'r', encoding="utf8") as input_file:
        old_file = input_file.readlines()

    # Discover index of old string you want to replace
    new_string_index = get_index(old_file, old_string)

    # Crates array with your new string formatted
    lines_to_write = [','.join(new_string.split())]

    # Populate lines_to_write array with lines formatted from the index you want
    for old_line in old_file[new_string_index + 1:]:
        new_line = old_line.strip().split()
        lines_to_write.append(','.join(new_line))

    # Write lines_to_write array to output file
    with open(out_file, 'w', encoding="utf8") as export_file:
        for line in lines_to_write:
            export_file.write(line)
            export_file.write('\n')


# Call function with your variables
if __name__ == "__main__":
    OldString = "temp1   temp2(a/b)      temp3(t)  temp4(x)"
    NewString = "temp1 temp2 temp3 temp4"
    inputFile = "Temp1.txt"
    exportFile = 'File1.txt'
    write_files(inputFile, exportFile, OldString, NewString)

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

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