python - 如何使用 Python 指定将哪些列打印到文本文件?

标签 python

这是我当前输出的示例:

['5216', 'SMITH', 'VICTORIA', 'F', '2009-12-19']

这是我的代码:

users1 = open('users1.txt','w')

with open('users.txt', 'r') as f:
    data = f.readlines()

    for line in data:
        words = str(line.split())
        #print words
        f.seek(0)
        users1.write(words)

我想读取 users.txt 并将信息分开以将其发送到 users1 和另一个我将调用的文本文件 users2。 (请记住,这是一种假设情况,我承认将这些信息分开是没有意义的,就像我在下面建议的那样。)

是否可以识别我想插入到每个文本文件中的特定列?

例如,如果我希望 users1.txt 包含,使用上面的示例输出,['5216','2009-12-19']users2.txt包含['SMITH','VICTORIA'],怎么办?

最佳答案

你可以 use slicing从列表中选择项目。例如,

In [219]: words = ['5216', 'SMITH', 'VICTORIA', 'F', '2009-12-19']

In [220]: [words[0], words[-1]]
Out[220]: ['5216', '2009-12-19']

In [221]: words[1:3]
Out[221]: ['SMITH', 'VICTORIA']

with open('users.txt', 'r') as f,\
     open('users1.txt','w') as users1,\
     open('users2.txt','w') as users2:
    for line in f:
        words = line.split()
        users1.write(str([words[0], words[-1]])
        users2.write(str(words[1:3])                     

在输出中包含括号 [] 是非标准的。 为了可移植性和正确处理带引号的字符串和包含逗号分隔符的字符串,您最好使用 csv module :

import csv
with open('users.txt', 'rb') as f,\
     open('users1.txt','wb') as users1,\
     open('users2.txt','wb') as users2:
    writer1 = csv.writer(users1, delimiter=',')
    writer2 = csv.writer(users2, delimiter=',')     
    for line in f:
        words = line.split()
        writer1.writerow([words[0], words[-1]])
        writer2.writerow(words[1:3])                

关于python - 如何使用 Python 指定将哪些列打印到文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23641838/

相关文章:

python - ELI5 Python groupby代码其中 "collapses"个连续数字

python - 我遇到了有关 AttributeError 的问题

python - 将 SQL 命令转换为 Python 的 ORM

python - Google 任务队列 REST 拉取偶尔返回 500

python - Pandas - 填充 NaN 的变体 - 什么是优雅和 pythonic 的方式来做到这一点?

python - 在python中设置环境变量来运行程序

python - B 中 A 的不同实例 (Python)

python - 在 pygame 中,当我与某物碰撞时如何位图传送图像并使其保持不变?

Python - 在曲线函数上方返回数组中的元素数

python - 使用 Pandas 将具有多行的数据框转换为一行?