![](/img/trans.png)
[英]Python - how to read txt file every xxx time and add to multiprocess if new text added
[英]python read text file and add strings and create new txt file
我有一个带有 pipe 分隔符的 txt 文件,如下所示:
a|b|c|d|e|f
d|f|g|h|j|k
我想从 txt 文件中读取值并分配一些列名,如下所示
data1 = index(1)
data2 = index(2)
data3 = index(3)
data4 = index(4)
data5 = index(5)
data6 = index(7)
data7 = "xyz"
data8 = "hgf"
data9 = "opi"
现在我想将所有内容写入新的文本文件,如下所示: data8|data9|data2|data3|data1|data5|data6|data4|data7|
任何帮助将不胜感激。
要写入文件,您所要做的就是打开一个,写入,然后关闭
f = open("name.txt", "w")
f.write(data8 + '|')
f.write(data9 + '|')
f.write(data2 + '|')
f.write(data3 + '|')
f.write(data1 + '|')
f.write(data6 + '|')
f.write(data4 + '|')
f.write(data7 + '|')
f.close()
该文件将在您运行程序的目录中创建。 如果要写入非字符串格式的数据,请在数据周围使用 str()。
您可以使用列表来保留值
例子:
#after reading the file - output "a|b|c|d"
out = "a|b|c|d"
out = out.split("|") #will output ["a", "b", "c", "d"]
#here you can change the values of the list
#re-creating string with separators
for i in range(0, len(out) * 2, 2):
out.insert(i, "|")
out = "".join(out)
这应该会给你想要的 output。 要打开文件,请执行此file = open("filename.ext", "(w) for write or (r) for read only")
,然后写入 do file.write("text")
,一次读取所有内容: file.read()
并获取行file.readlines(amount of lines to read - leave blank for all lines)
。 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.