简体   繁体   English

在python中拆分文本文件

[英]Splitting text file in python

I'm a beginner with Python and would appreciate some help.我是 Python 的初学者,希望得到一些帮助。 I'm having trouble with the code below as I can't split a file.我在使用下面的代码时遇到问题,因为我无法拆分文件。 In my text file I have Gem11 and Gem12 on separate lines and would like to know how to display it in Python in the same format without the quotation marks.在我的文本文件中,我将 Gem11 和 Gem12 放在不同的行上,我想知道如何在 Python 中以相同的格式显示它而不带引号。

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

Here's what python is generating.这是python正在生成的内容。 I'm trying to remove the quotation marks etc so I simply have Gem11 and Gem12 so I can then place these in a variable to search through later:我正在尝试删除引号等,所以我只有 Gem11 和 Gem12,然后我可以将它们放在一个变量中以供以后搜索:

['Gem11\n', 'Gem12\n']

Quotation marks are how python demarcates strings.引号是 python 划分字符串的方式。 The actual object string does not contain the quotations marks.实际的对象字符串不包含引号。 Try printing each string with print and you'll see those quotes disappear.尝试用print打印每个字符串,你会看到那些引号消失了。

The other thing to note is the trailing newline in your lines, because file lines are read in with the trailing newline by default, so you'll need to call str.strip() to get rid of it.另一件事要注意的是行中的尾随换行符,因为默认情况下文件行是用尾随换行符读入的,因此您需要调用str.strip()来摆脱它。 I'd recommend iterating over f , the file object, so doing this becomes easier.我建议迭代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)

Instead of using readlines, use readline.不要使用 readline,而是使用 readline。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM