当谈到python或一般编码时,我是个新手。我设置了一个脚本,读取各种.csv文件。我有一个私人笔记本和一个工作笔记本。
如何自动读取名为"1.txt"、"2.txt"…"22.txt"等文件的.csv?以及如何在用户名更改时根据系统/笔记本自动调整数据所在的路径。
c1 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid1.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c2 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid2.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c3 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid3.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c4 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid4.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c5 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid5.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c6 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid6.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c7 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid7.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
c8 = pd.read_csv(r"C:UserssaramDesktopworkspacedata20200108Solid8.txt", sep='t', header=0, skiprows=range1+range2, usecols=range3)
如果你能帮我,我将不胜感激;3
Sara
您可以使用字符串格式将数字放在{}
的位置
name = "path/filename{}.txt".format(number)
你可以在循环for number in range(1, 9):
中完成
您也可以使用列表将文件保存为c[0]
、c[1]
,因为您可以在其他循环中使用它们
c = []
for i in range(1, 9):
name = r"C:UserssaramDesktopworkspacedata20200108Solid{}.txt".format(i)
df = pd.read_csv(name, sep='t', header=0, skiprows=range1+range2, usecols=range3)
c.append(df)
您也可以使用os.listdir("folder")
获取文件名
import os
c = []
folder = r"C:UserssaramDesktopworkspacedata20200108Solid"
for name in os.listdir(folder)
if name.endswith('.txt')
fullname = os.path.join(folder, name)
df = pd.read_csv(fullname, sep='t', header=0, skiprows=range1+range2, usecols=range3)
c.append(df)
或glob.glob("folder/*.txt")
import glob
c = []
for fullname in glob.glob(r"C:UserssaramDesktopworkspacedata20200108Solid/*.txt")
df = pd.read_csv(fullname, sep='t', header=0, skiprows=range1+range2, usecols=range3)
c.append(df)