在python中拆分文本文件

时间:2017-10-15 18:03:17

标签: python python-3.x

我是Python的初学者,非常感谢一些帮助。我无法使用下面的代码,因为我无法拆分文件。在我的文本文件中,我在单独的行上有Gem11和Gem12,并且想知道如何在没有引号的相同格式下在Python中显示它。

 1.   It is recursive.

 2.   Drivers can request that Giant be locked around them by not marking
  themselves MPSAFE.  Note that infrastructure to do this is slowly
  going away as non-MPSAFE drivers either became properly locked or
  disappear.

 3.   Giant must be locked before other non-sleepable locks.

 4.   Giant is dropped during unbounded sleeps and reacquired after
  wakeup.

 5.   There are places in the kernel that drop Giant and pick it back up
  again.  Sleep locks will do this before sleeping.  Parts of the net-
  work or VM code may do this as well.  This means that you cannot
  count on Giant keeping other code from running if your code sleeps,
  even if you want it to.

这是python正在生成的内容。我正在尝试删除引号等,所以我只需要Gem11和Gem12,这样我就可以将它们放在变量中以便稍后搜索:

with open ("testpractice01.txt" , "r") as f: 
    f_contents = f.readlines()
    print (f_contents)
    f.close()

2 个答案:

答案 0 :(得分:2)

引号是python如何划分字符串。实际的对象字符串不包含引号。尝试使用print打印每个字符串,您会看到这些引号消失。

另外需要注意的是行中的尾部换行符,因为默认情况下会使用尾随换行符读入文件行,因此您需要调用str.strip()来删除它。我建议迭代文件对象f,这样做会变得更容易。

f_contents = []
with open ("testpractice01.txt" , "r") as f: 
    for line in f:
        f_contents.append(line.strip())

for line in f_contents:
    print(line)

答案 1 :(得分:0)

使用readline。而不是使用readlines。

with open ("test.txt" , "r") as f:
    for line in f:
        print (line)
    f.close()