python - 与预期不同的输出格式

标签 python python-2.7 python-3.x newline

我已经编写了代码来读取以下文本文件

Generated by trjconv : a bunch of waters t=   0.00000
 3000
    1SOL     OW    1  -1.5040   2.7580   0.6820
    1SOL    HW1    2   1.4788   2.7853   0.7702
    1SOL    HW2    3   1.4640   2.8230   0.6243
    2SOL     OW    4   1.5210   0.9510   2.2050
    2SOL    HW1    5  -1.5960   0.9780   2.1520
    2SOL    HW2    6   1.4460   0.9940   2.1640
 1000SOL     OW 2998   1.5310   1.7952   2.1981
 1000SOL    HW1 2999   1.4560   1.7375  -2.1836
 1000SOL    HW2 3000   1.6006   1.7369   2.2286
 3.12736   3.12736   3.12736
Generated by trjconv : a bunch of waters t= 9000.00000
 3000
    1SOL     OW    1   1.1579   0.4255   2.1329
    1SOL    HW1    2   1.0743   0.3793   2.1385

编写代码:

F = open('Data.gro', 'r')
A = open('TTT.txt', 'w')
XO = []
I = range(1, 10)
with open('Data.gro') as F:
    for line in F:
        if line.split()[0] == '3000':
            A.write('Frame' + '\n')
            for R in I:
                line = next(F)
                P = line.split()
                x = float(P[3])
                XO.append(x)
                if line.split()[2] == '3000':
                   print('Oxygen atoms XYZ coordinates:')
                   A.write('Oxygen atoms XYZ coordinates:' + '\n')
                   A.write("%s\n" % (XO))
                   XO
                   XO[0] - XO[1]
                   XO = []
               else:
                   pass
        else:
            pass


A.close()

第一个问题:

我的问题是在一行中输出文本文件如下所示。它在文本文件中打印为一行。

FrameOxygen atoms XYZ coordinates:[-1.504, 1.4788, 1.464, 1.521, -1.596, 1.446, 1.531, 1.456, 1.6006]FrameOxygen atoms XYZ coordinates:[1.1579, 1.0743, 1.1514, 2.2976, 2.2161, 2.3118, 2.5927, -2.5927, 2.5365]

输出应该如下所示。

Frame
Oxygen atoms XYZ coordinates:
[-1.504, 1.4788, 1.464, 1.521, -1.596, 1.446, 1.531, 1.456, 1.6006]
Frame
Oxygen atoms XYZ coordinates:
[1.1579, 1.0743, 1.1514, 2.2976, 2.2161, 2.3118, 2.5927, -2.5927, 2.5365]

但是当我阅读时,它会在每个分隔点的末尾显示“\n”。 有没有人有想法。

第二个问题

下一个问题是,这仅在我将粘贴代码复制到 python shell 中时才会产生。如果双击我的“code.py”文件,它不会生成输出文件。将粘贴代码复制到 python shell 时没有错误。

最佳答案

1) 您使用的是哪个平台和编辑器?

'\n' 应该按预期工作。

我怀疑您正在 Windows 中运行代码,并且您使用记事本检查了该文件。尝试使用写字板或其他功能更强大的编辑器打开 TTT.txt。结果应该符合预期。

2) 如果您在 MS Windows 中双击脚本,您很可能会错过一些由 python 打印的异常。尝试在命令提示符下运行它:

python code.py

关于python - 与预期不同的输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213304/

相关文章:

python - 从返回元组的函数创建新的 pandas 数据框列

python - 从模块名称获取路径

Python:如何在三个列表中找到共同的值

python-3.x - RAM 在 google colab 中崩溃

python - Python 3 中 print 和 click.echo 的区别?

python - 使用函数翻译数据帧时出错

python - PyQT5 - 警告使用 'exit' 、 'quit' 或 Ctrl-D 退出 jupyter notebook 中的应用程序

python-3.x - Python 3.7 非阻塞请求?

python - 如何按多个元素对字典列表进行排序

python - 根据Python中的条件从两个数组中随机选择