datas=[] def creat_pathcsv(): for dirname, _, filenames in os.walk('D:\学习\python learing\搜索引擎\TrainingReleased_CS\TrainingReleased_CS\STNO-UNICODE'): for filename in filenames: path = os.path.join(dirname, filename) # print(path) # print(type(path)) # print(dirname) path = str(path).replace("\\", "/") path = [path] datas.append(path) print(datas) datas中没有元素是为什么
时间: 2024-01-25 22:02:54 浏览: 30
这段代码定义了一个列表 datas,并定义了一个名为 creat_pathcsv 的函数,但是在函数中只是往 datas 列表中添加了元素,但是并没有调用这个函数。因此,如果你在代码中直接打印 datas 列表,那么它是空的。
如果你想要得到这个列表中的元素,需要在调用 creat_pathcsv 函数之后,再次打印 datas 列表,例如:
```
datas = []
def creat_pathcsv():
for dirname, _, filenames in os.walk('D:\学习\python learing\搜索引擎\TrainingReleased_CS\TrainingReleased_CS\STNO-UNICODE'):
for filename in filenames:
path = os.path.join(dirname, filename)
path = str(path).replace("\\", "/")
path = [path]
datas.append(path)
creat_pathcsv()
print(datas)
```
这样就可以得到包含文件路径的列表了。
相关问题
优化这段代码#csv_combline #encoding = utf-8 import os import csv path = "D:\csv_test\\" for files in os.listdir(path): datas = [] #读取csv文件 for fname in os.listdir(path): if 'csv' in fname: fname_path = path + fname with open(fname_path,'r',encoding = 'latin1') as path: reader = csv.reader(path) #去掉表头第0行,从第一行开始copy数据 reader = list(reader)[1:] for line in render: datas.append(line) eccel_name = 'excle汇总.csv' csv_head = ['name','aaa','bbb'] with open(excel_name,'w') as path: writer = csv.writer(path) #写表头 writer.writerow(csv_head) writer.writerows(datas) print('exlce.csv合并完成')
优化建议如下:
1. 将代码块封装成一个函数,提高代码的可重用性和可维护性。
2. 将常量和变量的命名方式统一,便于代码的阅读和理解。
3. 将文件路径的拼接方式改为os.path.join()方法,增强代码的跨平台兼容性。
4. 使用with语句打开文件,可自动管理文件资源,不需要手动关闭文件,简化代码。
5. 将csv文件读取和写入的编码方式改为'utf-8',避免出现中文乱码问题。
6. 将写入csv文件的表头和数据分别存储在两个列表中,遵循“单一职责原则”,增强代码的可读性和可维护性。
7. 将读取csv文件的代码块修改为生成器表达式,节省内存开销。
8. 将写入csv文件的操作放在try...except块中,避免出现写入失败的情况。
优化后的代码如下所示:
```python
import os
import csv
def combine_csv_files(src_dir, dest_file):
csv_head = ['name', 'aaa', 'bbb']
data_rows = []
try:
for file_name in os.listdir(src_dir):
if file_name.endswith('.csv'):
file_path = os.path.join(src_dir, file_name)
with open(file_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
next(reader) # skip header
data_rows.extend(reader) # append rows to data list
with open(dest_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(csv_head)
writer.writerows(data_rows)
print(f'CSV files in {src_dir} are combined into {dest_file}')
except Exception as e:
print(f'Error occurs: {e}')
if __name__ == '__main__':
src_dir = r'D:\csv_test'
dest_file = r'D:\csv_test\excle汇总.csv'
combine_csv_files(src_dir, dest_file)
```
# -*- mode: python ; coding: utf-8 -*- import os currentUrl = os.path.abspath(os.path.join("__file__")) SETUP_DIR = os.path.dirname(currentUrl)+"\\" def findAllFilesWithSpecifiedSuffix(target_dir, target_suffix="py"): find_res = [] target_suffix_dot = "." + target_suffix walk_generator = os.walk(target_dir) for root_path, dirs, files in walk_generator: if len(files) < 1: continue for file in files: file_name, suffix_name = os.path.splitext(file) if suffix_name == target_suffix_dot: find_res.append(os.path.join(root_path, file)) return find_res py_files = findAllFilesWithSpecifiedSuffix(SETUP_DIR) block_cipher = None a = Analysis(py_files, pathex=[SETUP_DIR], binaries=[], datas=[(SETUP_DIR+'Json_File','Json_File'),(SETUP_DIR+'Remote_file','Remote_file')], hiddenimports=['pyttsx3','pyserial','opencv-python','pillow','openpyxl'], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='host_structure', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=False, disable_windowed_traceback=False, target_arch=None, codesign_identity=None, entitlements_file=None) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='TCLtester')报错:ValueError: the environment variable is longer than 32767 characters
这个错误通常是因为环境变量字符串太长了,超过了 Windows 系统的限制(32767 个字符)。这可能是由于你添加了太多的路径或其他信息到环境变量中。
你可以尝试以下方法来解决这个问题:
1. 删除一些不必要的环境变量,或者将其中一些路径移动到其他地方,以减少环境变量字符串的长度。
2. 将一些常用的路径添加到 Python 的 `sys.path` 中,而不是添加到环境变量中。这样可以避免环境变量字符串过长的问题,也可以更好地控制 Python 的搜索路径。
3. 如果你需要使用很多路径,可以尝试将它们分成几个较短的字符串,然后在 Python 中使用 `os.environ` 设置多个环境变量。例如:
```python
import os
path1 = r'C:\path1'
path2 = r'C:\path2'
path3 = r'C:\path3'
# 将路径拆分成多个较短的字符串
chunks = [path1, path2, path3]
# 将每个字符串添加到环境变量中
for i, chunk in enumerate(chunks):
varname = f'MYPATH_{i}'
os.environ[varname] = chunk
# 在 Python 中使用这些环境变量
import sys
sys.path.append(os.environ['MYPATH_0'])
sys.path.append(os.environ['MYPATH_1'])
sys.path.append(os.environ['MYPATH_2'])
```
这样做可以避免环境变量字符串太长的问题,同时也可以更好地控制 Python 的搜索路径。