Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除一列文本_Python - Fatal编程技术网

Python 删除一列文本

Python 删除一列文本,python,Python,我对Python完全陌生,但我有一些其他语言的脚本编写经验。我正在尝试编写一个脚本,用于读取包含如下格式数据的文本文件: 1 52345 2 53 3 -654 4 2342 52345, 53, -654, 2342, 然后像这样打印出来: 1 52345 2 53 3 -654 4 2342 52345, 53, -654, 2342, 因此,我想删除第一列和空格,并在末尾添加逗号 这就是我到目前为止所拥有的,但似乎我正在尝试对文件对象

我对Python完全陌生,但我有一些其他语言的脚本编写经验。我正在尝试编写一个脚本,用于读取包含如下格式数据的文本文件:

1    52345
2    53
3    -654
4    2342
52345,
53,
-654,
2342,
然后像这样打印出来:

1    52345
2    53
3    -654
4    2342
52345,
53,
-654,
2342,
因此,我想删除第一列和空格,并在末尾添加逗号

这就是我到目前为止所拥有的,但似乎我正在尝试对文件对象使用字符串方法

def remove_first_column(text):
    splitString = text.split(' ')

    splitString.pop(0)


    finalString = "  ".join(
        [item.strip() for item in splitString])

    return finalString

def main():
    print "Type the filename:"
    file_again = raw_input("> ")
    txt = open(file_again)
    for line in txt.split("\n"):
        print(remove_first_column(line))  #py2.5  print remove_first_column(line)

if __name__ == '__main__':
    main()

我遇到了一个异常,即“AttributeError:'file'对象没有属性'split'”

您不能拆分文件对象:

for line in txt:

txt
是一个文件对象,不是字符串。您可以试试

for line in txt:
而不是

for line in txt.split("\n"):

是的,当您使用
open
函数打开一个文件时,它会返回一个文件对象,您可以迭代文件对象(以获取每一行),但不能使用
file.split('\n')

试着做-

for line in txt:
    print(remove_first_column(line))  #py2.5  print remove_first_column(line)
您不需要
拆分
,在
txt
文件上迭代将返回每次迭代中的每一行

另外,在函数内部,您正在执行-
splitString=text.split(“”)
,如果字符串在两列之间有多个空格,这可能会导致许多空字符串元素,如-
['1','','','','','','52345']
(尽管这不会导致特定代码中出现问题),只是让您知道,您可以执行-
splitString=text.split()
,以按所有空格进行分割,(这将产生一个类似-
['1','52345']

的列表,该列表可能与