python中的列表和txt文件问题

辣条钵 发布于 2016/02/17 20:30
阅读 1K+
收藏 0

有一个man.txt文件,里面是一个大的列表:

['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', .....(省略若干)]

现在想把这个对话给以一句话一行的形式打印到另一个txt文件里,我是这样写的:

import sys

def print_lol(the_list,fn = sys.stdout):

    for each_item in the_list:

        print(each_item,end = '',file = fn)


然后在shell里:

with open('man.txt') as data, open('test.txt','w') as file:

#这里的test.txt就是存放处理后数据的txt文件。

   print_lol(data,fn = file)


但是运行之后,test.txt中虽然有东西,但是格式和之前一模一样,如何才能打印成如下样子呢?

Is this the right room for an argument?

No you haven't!

When?

.....

...

这是Head first python中的第四章的题目,大概在126页附近,如果觉得我问题描述的不清楚,可以百度一下这本书的电子版,谢谢!

谢谢!

加载中
0
北京老爷们儿
北京老爷们儿
import json
with open("D:/main.txt","r") as data1, open("D:/test.txt","a") as data2:
    info = data1.readline()
    for x in json.loads(info):

        data2.write(x+"\n")

在这用了一个json,因为你读进来的貌似是list,其实是'["a","b"]',是个文本类型,需要转换为list

辣条钵
好像不行,idle报了很长的几段错误。好像是json出错了。如果把json去掉,直接readline后print(info)则就是每一个字符一行。
0
铂金胖子
铂金胖子
import demjson
铂金胖子
铂金胖子
回复 @辣条钵 : python自己的json 无法解析你上面的那个, 用demjson 可以
辣条钵
意思是用json吗?谢谢!
0
从前是菜鸟
从前是菜鸟
with open('man.txt') as man:
    with open('new.txt', 'w') as new:
        for i in man.read().split(','):
            new.write(i[2:(len(i) - 1)] + '\n')



0
从前是菜鸟
从前是菜鸟

上面发的代码执行后最后一个字符串元素的右边会有一个分号,故增加一个 if...else...改成下面的就没问题了。

with open('man.txt') as man:
    with open('new.txt', 'w') as new:
        tmp = man.read().split(',')
        for i in tmp:
            if i != tmp[-1]:
                new.write(i[2:(len(i) - 1)] + '\n')
            else:
                new.write(i[2:(len(i) - 2)])



运行结果如下:

Is this the right room for an argument?
No you haven't!
When?
No you didn't!
You didn't!
You did not!





辣条钵
十分感谢!
0
幻视Vision
幻视Vision

直接读取后exec

之前盲写的,没有测试。刚发现需要拼接一个变量进去接受list的结果才行。


with open("man.txt") as f1,open("test.txt","w+") as f2:
    txt=f1.read().rstrip("\n")
    exec(r"man="+txt)
    print(man)
    [f2.write(r+"\n") for r in man]



辣条钵
谢谢~~
-1
fighting-cluber
fighting-cluber
cat man.txt | xargs -d , -n 1



辣条钵
虽然不太懂。但还是非常感谢!
返回顶部
顶部