简体   繁体   English

Python-如何从文件中删除列

[英]Python- How to Remove Columns from a File

I'd like to remove the first column from a file. 我想从文件中删除第一列。 The file contains 3 columns separated by space and the columns has the following titles: X', 'Displacement' and 'Force' (Please see the image). 该文件包含3列,各列之间用空格隔开,并且这些列具有以下标题:X','Displacement'和'Force'(请参见图片)。

资料档案

I have came up with the following code, but to my disappointment it doesn't work! 我提出了以下代码,但令我失望的是,它不起作用!

f = open("datafile.txt", 'w')
 for line in f:
  line = line.split()
  del x[0]
f.close()

Any help is much appreciated ! 任何帮助深表感谢 ! Esan 易山

First of all, you're attempting to read from a file (by iterating through the file contents) that is open for writing. 首先,您正在尝试从文件中读取(通过遍历文件内容)以进行写入。 This will give you an IOError . 这将给您一个IOError

Second, there is no variable named x in existence (you have not declared/set one in the script). 其次,不存在名为x变量(您尚未在脚本中声明/设置一个)。 This will generate a NameError . 这将生成一个NameError

Thirdly and finally, once you have finished (correctly) reading and editing the columns in your file, you will need to write the data back into the file. 第三,也是最后,一旦(正确)读取和编辑文件中的列,您将需要将数据写回到文件中。

To avoid loading a (potentially large) file into memory all at once, it is probably a good idea to read from one file (line by line) and write to a new file simultaneously. 为了避免将一个(可能很大的)文件一次全部加载到内存中,从一个文件(逐行)读取并同时写入一个新文件可能是一个好主意。

Something like this might work: 这样的事情可能会起作用:

f = open("datafile.txt", "r")
g = open("datafile_fixed.txt", "w")

for line in f:
    if line.strip():
        g.write("\t".join(line.split()[1:]) + "\n")

f.close()
g.close()
print ''.join([' '.join(l.split()[1:]) for l in file('datafile.txt')])

或者,如果您想保留空格并且知道第二列始终以第10个字符开头:

print ''.join([l[11:] for l in file('datafile.txt')])

Some reading about python i/o might be helpful, but something like the following should get you on your feet: 读一些有关python i / o的信息可能会有所帮助,但是类似以下内容的内容应该可以帮助您:

with open("datafile.txt", "r") as fin:
    with open("outputfile.txt", "w") as fout:
        for line in fin:
            line = line.split(' ')
            if len(line) == 3:
                del line[0]
                fout.write(line[0] + ' ' + line[1])
            else:
                fout.write('\n')

EDIT: fixed to work with blank lines 编辑:固定为使用空白行

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

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