[英]Run a Python script on every text file in a folder using Spyder
I am trying to run a script onto over 900 files using the Spyder platform, that aims to delete the first 3 rows of data and certain columns.我正在尝试使用 Spyder 平台在 900 多个文件上运行脚本,目的是删除前 3 行数据和某些列。 I tried looking into other similar questions but was unable to achieve the intended results.
我尝试研究其他类似的问题,但无法达到预期的结果。
My code for one text file is as follows:我的一个文本文件的代码如下:
import pandas as pd
mydataset = pd.read_csv('vectors_0001.txt')
df = pd.DataFrame(mydataset)
df.drop(df.iloc[:,:2], inplace = True, axis = 1)
df.drop([0,1,3], axis = 0, inplace = True)
df = df.dropna(axis = 0, subset=['Column3','Column4'])
Then I want to modify the code above so it can be applied to the consecutive text files, all the text file names are: vectors_0001, vectors_0002, ..., vectors_0900.然后我想修改上面的代码,使它可以应用于连续的文本文件,所有的文本文件名是:vectors_0001、vectors_0002、...、vectors_0900。 I tried to do something similar but I keep getting errors.
我试图做类似的事情,但我不断收到错误。 Take the one below as an example: (Note: that 'u [m/s]', 'v [m/s]' are the columns I want to keep for further data analysis and the other columns I want to get rid of.)
以下面的一个例子为例:(注意:'u [m/s]', 'v [m/s]'是我想保留用于进一步数据分析的列,其他列我想去掉.)
import glob
import os.path
import sys
import pandas as pd
dir_of_interest = sys.argv[1] if len(sys.argv) > 1 else '.'
files = glob.glob(os.path.join(dir_of_interest, "*.txt"))
for file in files:
with open('file.txt', 'w') as f:
f.writelines(3:)
df = pd.read_csv("*.txt")
df_new = df[['u [m/s]', 'v [m/s]']
df_new.to_csv('*.txt', header=True, index=None)
with open('file.txt','r+') as f:
print(f.read())
However I tried to run it and I got the error:但是我尝试运行它,但出现错误:
f.writelines(3:)
^
SyntaxError: invalid syntax
I really want to get this figured out and move onto my data analysis.我真的很想弄清楚这一点,然后继续我的数据分析。 Please and thank you in advance.
请提前谢谢你。
I'm not totally sure of what you are trying to achieve here but you're using the writelines functions incorrectly.我不完全确定您要在这里实现什么,但是您错误地使用了 writelines 函数。 It accepts a list as an argument
它接受一个列表作为参数
https://www.w3schools.com/python/ref_file_writelines.asp https://www.w3schools.com/python/ref_file_writelines.asp
You're giving it "3:" which is not valid.你给它“3:”这是无效的。 Maybe you want to give it a fraction of an existing list ?
也许你想给它一个现有列表的一小部分?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.