如何将每一行分成两个字符串并打印而不带逗号?

时间:2020-05-24 06:38:26

标签: python

我正在尝试使输出没有逗号,并将每行分成两个字符串并打印。

到目前为止,我的代码产生了:

173,70
134,63
122,61
140,68
201,75
222,78
183,71
144,69

但是我希望它打印出来时不带逗号,并且每一行的值都被分隔为字符串。

if __name__ == '__main__':
    # Complete main section of code

    file_name = "data.txt"

    # Open the file for reading here

    my_file = open('data.txt') 

    lines = my_file.read() 

    with open('data.txt') as f:
        for line in f:

            lines.split()
            lines.replace(',', ' ')

    print(lines)

3 个答案:

答案 0 :(得分:2)

在示例代码中,linestr的形式包含了文件的全部内容。

my_file = open('data.txt') 
lines = my_file.read() 

然后,您稍后重新打开文件以迭代各行:

with open('data.txt') as f:
    for line in f:
        lines.split()
        lines.replace(',', ' ')

但是请注意,str.splitstr.replace不会修改现有值,例如strs in python are immutable。另外请注意,您正在此处lines上操作,而不是在for循环变量line上操作。

相反,您需要将这些函数的结果分配为新值,或将其作为参数(例如,给print)。因此,您需要打开文件,遍历各行,并用","替换为" "来打印值:

with open("data.txt") as f:
    for line in f:
        print(line.replace(",", " "))

或者,因为无论如何您都在处理整个文件:

with open("data.txt") as f:
    print(f.read().replace(",", " "))

或者,由于文件看起来是CSV内容,因此您可能希望使用标准库中的csv module

import csv

with open("data.txt", newline="") as csvfile:
    for row in csv.reader(csvfile):
        print(*row)

答案 1 :(得分:0)

with open('data.txt', 'r') as f:
    for line in f:
        for value in line.split(','):
            print(value)

答案 2 :(得分:0)

尽管python可以为我们提供几种打开文件的方式,但是这是处理文件的首选方式。因为我们正在以惰性模式打开文件(这是大型文件的首选),并且退出 with 范围(标识块)后,文件 io 将由系统自动关闭。

在这里,我们以读取模式打开文件。文件遵循迭代器策略,因此我们可以像列表一样遍历它们。每行是文件中的真行,并且是字符串类型。

获取该行之后,在 line 变量中,我们将该行拆分(请参阅str.split())为2个标记,一个标记在逗号之前,另一个标记在逗号之后。 split返回新构造的字符串列表。如果您需要省略一些多余的字符,可以使用str.strip() method。通常将剥离和拆分结合在一起。

优雅高效的文件读取-方法1

with open("data.txt", 'r') as io:
    for line in io:  
        sl=io.split(',')                      # now sl is a list of strings. 
        print("{} {}".format(sl[0],sl[1]))    #now we use the format, for printing the results on the screen.

非优雅但有效的文件读取-方法2

fp = open("data.txt", 'r')
line = None
    while (line=fp.readline()) != '':  #when line become empty string, EOF have been reached. the end of file!
        sl=line.split(',')                     
        print("{} {}".format(sl[0],sl[1]))