Python 按升序将提取的列保存到txt文件

Python 按升序将提取的列保存到txt文件,python,pandas,sorting,text,Python,Pandas,Sorting,Text,我需要一些帮助,以升序将值从列写入文本文件 我当前拥有的代码创建了一个名为values的目录,并将从列中提取的值保存到.txt文件中,但它不是我想要的升序 values\u dir=os.path.join(cwd,'values') 如果操作系统路径不存在(值\u dir): os.mkdir(值\u dir) 打开(os.path.join(values_dir,'values.txt'),“w”)作为txt_文件: 对于名称,拆分位置中的组: txt_file.write(str(name

我需要一些帮助,以升序将值从列写入文本文件

我当前拥有的代码创建了一个名为
values
的目录,并将从列中提取的值保存到.txt文件中,但它不是我想要的升序

values\u dir=os.path.join(cwd,'values')
如果操作系统路径不存在(值\u dir):
os.mkdir(值\u dir)
打开(os.path.join(values_dir,'values.txt'),“w”)作为txt_文件:
对于名称,拆分位置中的组:
txt_file.write(str(name)+'\n')
代码将我的值保存为

data23
data17
data88
我想把它另存为

data17
data23
data88
如果有人能给我指出正确的方向,我将不胜感激,谢谢

编辑 我在
Data
Data\u Unit

datafile=pd.read\u csv('location.csv'))
数据文件\u large=pd.read\u csv('large.csv'))
split_location=datafile.groupby('Data'))
split\u large=datafile\u large.groupby('Data\u Unit'))
然后,我循环遍历这些组,并根据它们的唯一值将分割的数据帧保存到子目录中,同时保留父文件名

对于名称,组位于拆分位置:
sub_dir=os.path.join(cwd,名称)
如果操作系统路径不存在(子目录):
os.mkdir(sub_dir)
group=group.drop(['Data'],轴=1)
group.to_csv(sub_dir+“/location.csv”,索引=0)
对于名称,拆分为大的组:
sub_dir=os.path.join(cwd,名称)
如果操作系统路径不存在(子目录):
os.mkdir(sub_dir)
group=group.drop(['Data\u Unit',轴=1)
group.to_csv(sub_dir+“/large.csv”,索引=0)
最后,我创建了开头提到的
values.txt
文件。但希望将值按升序保存在.txt文件中

values\u dir=os.path.join(cwd,'values')
如果操作系统路径不存在(值\u dir):
os.mkdir(值\u dir)
打开(os.path.join(values_dir,'values.txt'),“w”)作为txt_文件:
对于名称,拆分位置中的组:
txt_file.write(str(name)+'\n')
试试这个:

名称,组=地图(列表,邮编(*拆分位置))
names.sort()
对于名称中的名称:
txt_file.write(str(name)+'\n')
而不是:

对于名称,组位于拆分位置:
txt_file.write(str(name)+'\n')

您可以使用python内置的
sorted
函数或列表的
sort
方法。另一个答案显示了排序方法,所以我在这里使用sorted

对python 3也使用
pathlib

from pathlib import Path

values_dir = Path.home() / 'values'
values_dir.mkdir(exist_ok=True)

# step one: get a list of names
# from your example, split_location looks like
# an iterable of two-item tuple or list
names = sorted([str(item[0]) for item in split_location])

# step two: write the list of sorted names
# you can write just one string by joining your
# list of names with newline characters
newf = values_dir / 'values.txt'
newf.write_text('\n'.join(names))

非常感谢您的回答:)不幸的是,这些值仍然没有按升序保存,我无法理解它
split\u location
是什么样子的?我添加了一些编辑,以便对我试图实现的目标进行更广泛的解释。再次感谢@MadyDaby@Kam-ALIEN是否将原来的for循环更改为拆分位置中的名称、组的
。排序值(“数据”):
有效?我以前尝试过此方法,但出现了AttributeError:“DataFrameGroupBy”对象没有属性“排序值”…感谢您的回复