I am writing a script to change the formatting of the text from one file, and create a new text file with the changes in formatting. I have been able to remove unwanted characters, but haven't found a way to append text to the beginning of every line in the file.
我正在编写一个脚本来更改一个文件中文本的格式,并创建一个包含格式更改的新文本文件。我已经能够删除不需要的字符,但还没有找到一种方法将文本追加到文件中每一行的开头。
Content from the original file looks like:
原始文件中的内容如下所示:
DMA 123 USA 12345
What I need it to look like after appending data to the start, middle, and end of the string:
将数据附加到字符串的开头,中间和结尾后,我需要它看起来像什么:
<option label="DMA 123 USA" value="123"></option>
I have almost 100 lines that vary some, but follow the above formatting. I am trying to automate this as it will be a frequent task to adjust the original file to the new format for web publishing
我有近100行不同,但按照上面的格式。我正在尝试自动执行此操作,因为将原始文件调整为Web发布的新格式将是一项常见任务
I have been searching and haven't found any way to do it yet. Here is my current code:
我一直在寻找,但还没有找到任何办法。这是我目前的代码:
path = 'file.txt'
tvfile = open(path,'r')
days = tvfile.read()
new_path = 'tvs.txt'
new_days = open(new_path,'w')
replace_me = ['-' ,'(' ,')' ,',' , '"' , ]
for item in replace_me:
days = days.replace(item,'')
days = days.strip()
new_days.write(days)
print(days)
tvfile.close()
new_days.close()
1 个解决方案
#1
0
Nit: you need to prepend, not append. That said, try something along these lines:
尼特:你需要前置,而不是附加。也就是说,尝试以下几点:
buffer = ""
for item in replace_me:
line = "<option label=\""
line = line + days.replace(item,'').strip()
line = line + "\"></option>"
buffer = buffer + line
new_days.write(buffer)
#1
0
Nit: you need to prepend, not append. That said, try something along these lines:
尼特:你需要前置,而不是附加。也就是说,尝试以下几点:
buffer = ""
for item in replace_me:
line = "<option label=\""
line = line + days.replace(item,'').strip()
line = line + "\"></option>"
buffer = buffer + line
new_days.write(buffer)