简体   繁体   English

读取文件并在每个“;”之后添加NewLine

[英]Reading a file and adding NewLine after every “;”

I have a hobby CNC machine with a strangely written software. 我有一台业余数控机床,上面写着一个奇怪的软件。 In order to use it, I need to take my file that is outputted by a CAD software and add a new line (CRLF) after every ";". 为了使用它,我需要获取由CAD软件输出的文件,并在每个“;”之后添加新行(CRLF)。 I wanted to make a python script that would do this instead, but I can't get it to work. 我想制作一个Python脚本来代替它,但是我无法使其正常工作。 Can anyone point me in the right direction? 谁能指出我正确的方向?

import os
import sys

if not (len(sys.argv) == 2 and os.path.isfile(sys.argv[1])):
    print(__doc__)
    sys.exit(1)

file_in = open(sys.argv[1], "r+")
currentChar = file_in.read(1)
i = 0
while not currentChar:
    if (currentChar == ";"):
        file_in.seek(i)
        file_in.write("\n")
    currentChar = file_in.read(1)
    i += 1
file_in.close()

As mentioned by CristiFati's comment, you should read the file, close it and then open it for writing: 正如CristiFati的评论所提到的,您应该阅读文件,将其关闭,然后打开以进行写入:

import sys

file_in = open(sys.argv[1],'r')
content = file_in.read()
file_in.close()
file_out = open(sys.argv[1],'w')
file_out.write(content.replace(';',';\n'))
file_out.close()

Optionally you can change the output filename to be something different so that you don't overwrite your original file. (可选)您可以将输出文件名更改为其他名称,以免覆盖原始文件。

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

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