gpt4 book ai didi

linux - 如何使用python水平反转ctl文件中的文本数据并保存在新文件中?

转载 作者:太空狗 更新时间:2023-10-29 12:41:32 24 4
gpt4 key购买 nike

**我有一个 ctl 文件,包含如下所示的文本

mycnf_001/mycnf_001_001mycnf_001/mycnf_001_002............................................................(一个很长的列表,有 1000 行)

我很努力,但我无法获得我想要的格式

mycnf_001_001 mycnf_001mycnf_001_002 mycnf_001............................................................(一个很长的列表,有 1000 行)

********* 详细的问题描述***************************

当前格式 mycnf_001/mycnf_001_001

期望从 mycnf_001_001 mycnf_001

//////////代码////////////////////

f = open("ms.ctl", "rb")
s = f.readlines()
f.close()
f = open("newms.ctl", "wb")
s.reverse()
for item in s:
print>>f, item
f.close()

当我执行上面的代码时,它只是从下到上颠倒了顺序,我需要的在上面已经清楚地提到了。

最佳答案

让我们假设在读取文件“ms.ctl”后你有类似的值

s="mycnf_001/mycnf_001_001/mycnf_001_002"

现在根据'/'拆分字符串

spliteds = [x for x in s.split('/') if x.strip()]

现在你有了字符串数组。现在尝试从最后访问数组并将其保存在另一个字符串中。

desireds=""
for i in reversed(spliteds):
desireds = desireds + i + " "

现在您可以将此字符串放入任何文件中。

代码:

    f = open("ms.ctl", "rb")
s = f.read()
f.close()

N = s.split('\n')

f = open("newms.ctl", "wb")

spliteds = [ x for x in N[0].split('/') if x.strip()]
desireds=""
for i in reversed(spliteds):
desireds = desireds + i + " "
#print desireds

f.write(desireds)
f.close()

您可以使用 print 调试此代码。希望能帮助到你。

UPDATE

如果你想运行多行。

f = open("ms.ctl", "rb")
s = f.read()
f.close()

N = s.split('\n')
lenth = len(N)

f = open("newms.ctl", "wb")

for x in range(0, lenth):
print "We're on time %d" % (x)
spliteds = [ x for x in N[0].split('/') if x.strip()]
desireds=""
for i in reversed(spliteds):
desireds = desireds + i + " "
#print desireds
f.write(desireds)
f.close()

如果你想得到一列的输出。

在上面的代码中,只需将 desireds = desireds + i + "" 中的 "" 替换为 "\n" 即可

f = open("ms.ctl", "rb")
s = f.read()
f.close()

N = s.split('\n')
lenth = len(N)

f = open("newms.ctl", "wb")

for x in range(0, lenth):
print "We're on time %d" % (x)
spliteds = [ x for x in N[0].split('/') if x.strip()]
desireds=""
for i in reversed(spliteds):
desireds = desireds + i + "\n"
#print desireds
f.write(desireds)
f.close()

关于linux - 如何使用python水平反转ctl文件中的文本数据并保存在新文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41889773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com