python 学习遇到棘手问题那位高手指点下哪里出问题了?

import os

import shutil

def walkFile(file):

for root,dir,files in os.walk(file):

    # root 表示当前正在访问的文件夹路径

    # files 表示该文件夹下的文件list

    # dir 表示目前的文件夹

    # 遍历文件

    for f in files:    

            print(f[0:-4])   # 从遍历的文件去掉后缀名(.doc),如果后缀名是(.docx)那么切片更改为[0:-5].

word = "C:/Users/dvs909/Desktop/列表.txt"   # 设置读取文本的路径

with open (word) as obje:    

    f_words = obje.readlines()   # 读取文本内容作为列表储存

    for f_word in f_words:      # 遍历列表内容

        print(f_word.strip())   # 打印列表内容并去除空格

    while f[0:-4] == f_word.strip():   # 判断列表名是否等于文件名

        file_dir = "C:/Users/dvs909/Desktop/文件夹2" # 设置粘贴的文件路径

        shutil.copyfile(f,file_dir)  # 将文件粘贴到文件夹2路径

walkFile(“C:/Users/dvs909/Desktop/文件1”)

讨论数量: 12
Jason990420

大概的问题有:

  1. 一次能确定的, 不要放到回路中重复处理
  2. 判断列表名是否等于文件名, 不是用while, 而是if, 你用了while, 因为条件f[0:-4] == f_word.strip() 没有变, 会一直重复执行, 跳不出来.
  3. “C:/Users/dvs909/Desktop/ 文件 1”, "文件"前有一个空格, 肯定是不符合档案路径的要求.

我重写了一下, 没有试过, 你试试...

import os
from pathlib import Path
import shutil

def walkFile(file):

    for root, dir, files in os.walk(file):
        """
        Check all files if filename without suffix in list f_words.
        If true, copy file into directory file_dir
        """
        for f in files:
            # Check if filename without extension in list f_words
            # Path(f).stem get the filename without its suffix
            if Path(f).stem in f_words:
                # Copy file f to file_dir
                shutil.copyfile(f, file_dir)

dir       = "C:/Users/dvs909/Desktop/文件 1"      # Directory to search files
word      = "C:/Users/dvs909/Desktop/列表.txt"    # File list to copy
file_dir  = "C:/Users/dvs909/Desktop/文件夹2"     # Destination for files

# encoding may be different, it depends on how you save your word file
with open(word, 'rt', encoding='utf-8-sig') as obje:
    # Read lines from word, then apllied str.strip method and converted to list
    f_words = list(map(str.strip, obje.readlines()))

walkFile(dir)
5年前 评论

首先非常感谢的指点,但是运行还是出现以下错误,我用的是vscode Traceback (most recent call last): File "c:\Users\dvs909.vscode\extensions\ms-python.python-2020.2.64397\pythonFiles\ptvsd_launcher.py", line 48, in main(ptvsdArgs) File "c:\Users\dvs909.vscode\extensions\ms-python.python-2020.2.64397\pythonFiles\lib\python\old_ptvsd\ptvsd_main_.py", line 432, in main run() File "c:\Users\dvs909.vscode\extensions\ms-python.python-2020.2.64397\pythonFiles\lib\python\old_ptvsd\ptvsd_main_.py", line 316, in run_file
runpy.run_path(target, run_name='main') File "D:\python\lib\runpy.py", line 263, in run_path return _run_module_code(code, init_globals, run_name, File "D:\python\lib\runpy.py", line 96, in _run_module_code _run_code(code, mod_globals, init_globals, File "D:\python\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "d:\py\demo.py", line 29, in walkFile(dir) File "d:\py\demo.py", line 18, in walkFile shutil.copyfile(f, file_dir) File "D:\python\lib\shutil.py", line 259, in copyfile with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst: FileNotFoundError: [Errno 2] No such file or directory: '234.doc'

5年前 评论
Jason990420

是我忘了把路径加上去, 所以找不到档案

shutil.copyfile(f, file_dir)

改为

shutil.copyfile(Path(root).joinpath(f), file_dir)
5年前 评论

出现 [Errno 13] Permission denied: 'C:/Users/dvs909/Desktop/文件夹2' 似乎是权限被拒绝还是找不到文件,楞是没有找到问题,

5年前 评论
Jason990420

要清楚描问题, 并说明情况, 还要提供你知道的资讯. 比如:

  1. shutil.copyfile(f, file_dir) 出错
  2. [Errno 13] Permission denied: 'C:/Users/dvs909/Desktop/ 文件夹 2'
  3. f 的值为 'C:/Users/dvs909/Desktop/文件 1/文件 A/文件B.txt'
  4. 这个档案你有没直接试过能不能copy
  5. 其他你试过的情况

通常, 我只能说通常, 有些目录或档案是你动不了的, 极可能是系统目录或档案. 只能避过不动.

try:
    shutil.copyfile(f, file_dir)
except:
    pass
5年前 评论

谢谢,我想完成的是通过txt文本里面的字符提取一个文件夹里面相对应的相同名称的文件,复制到另一个文件夹,这样的功能,然后最后最后生成一个excel表格显示多少提取成功,多少提取失败,有bat可以实现,但是python经常报错,我想应该是python处理此类工作更胜一筹。下面是代码bat代码。
@echo off
set “原文件夹=F:\文件1”
set “新文件夹=E:\新建文件夹”
set “结果1=找到.csv”
set “结果2=未找到.csv”
cd /d “%dp0”
del /a /f /q “%结果1%” “%结果2%”
md “%新文件夹%” 2>nul
for /f “delims=” %%a in (‘type “列表.txt”‘) do (
set /a “a+=1,b=0”
set “f=”
for /f “delims=” %%b in (‘dir /a-d/b/s “%原文件夹%%%a.*”‘) do (
if “%%
xb” neq “” (
set /a b+=1
echo;”%%b” –^> “%新文件夹%"
xcopy “%%b” “%新文件夹%"
>>”%结果1%” echo;”%%b”
set f=1
)
)
if defined f (set /a c+=1) else (>>”%结果2%” echo;”””%%a”&set /a d+=1)
)
echo;总%a%,找到%c%,未找到%d%
pause
通过列表txt本文内容查找原文件夹里面的内容,然后复制到新文件夹,生成成功多少和失败多少。

5年前 评论
Jason990420

代码里面会有一些是markdown的保留字符, 会消失看不见的, 你最好用
```
代码
```
来PO文, 不然连你这bat档内容都不对了.
能用文字描述吗? 文字说明更直接吧.

5年前 评论

1.首先有代码所在路径有一个txt文本 2.打开txt文本内容 3.文本里面内容假如第一行有65123654内容 4.对照所在路径文件夹1里面是否有65123654.doc的word文件 5.假如有65123654.doc的文件则复制到所在路径文件夹2里面 6.生成csv格式报告,txt文本内容多少条内容找到多少条内容未找到,哪些内容没有找到。 这个就是上面的批处理脚本实现的功能,但是python脚本应该也可以实现,但是一直报错我在一直修改代码和百度,就是实现不了,原因是我python技术太菜。

5年前 评论
Jason990420

For your reference

  1. Output File
   Found for items in 列表.txt
   test,文件夹 1\dir1\test.txt,文件夹 1\dir2\test.txt
   test1,文件夹 1\dir1\test1.txt  

   Not found for items in 列表.txt


   5 Files in 文件夹 1
   3 Files in 文件夹 1 found
   2 Files in 文件夹 1 not found
  1. Source Code
import os
from pathlib import Path

def read_file(path):
    """
    read txt file into list
    - Sorted
    - Duplicate removed
    - Null lines removed
    - Remove white spaces at the beginning and at the end of the string
    """
    with open(path, 'rt') as f:
        lines = f.readlines()
    lines = list(set(map(str.strip, lines)))
    return sorted([line for line in lines if line != ''])

def search_files(path):
    """
    Search all files with absolute-path under path into list
    """
    result = []
    for root, directory, files in os.walk(path):
        result += [Path(root).joinpath(file) for file in files]
    return result

def file_not_exist(path):
    """
    Check if a file exist or not
    """
    return False if path.is_file() else True

def dir_not_exist(path):
    """
    Check if a directory exist or not
    """
    return False if path.is_dir() else True

def move_files(result, path):
    """
    Move files from all files to directory path
    - If same filename exist, rename with (index), like (2), (3), ...
      Warning message to user.
    - If fail when move file, skip and also with warning message.
    """
    for files in result.values():
        for file in files:
            i = 1
            p = path.joinpath(file.name)
            while p.is_file():
                i += 1
                p = path.joinpath('%s(%s)%s'%(file.stem, str(i), file.suffix))
            try:
                file.rename(p)
                if i != 1:
                    print('Duplicate, %s has been renamed as %s'%(
                        str(path.joinpath(file.name)), str(p)))
            except:
                print('%s cannot be copied into %s'%(str(file), str(path)))


path1       = Path('文件夹 1')
path2       = Path('文件夹 2')
list_file   = Path('列表.txt')
result_file = Path('結果.csv')

if file_not_exist(list_file):
    # If 列表.txt not exit, quit !
    print('"%s" file not found !'%str(list_file))
    quit()

if dir_not_exist(path1):
    # If 文件夹 1 not exist, quit !
    print('"%s" directory not found !'%str(path1))
    quit()

if dir_not_exist(path2):
    # If 文件夹 2 not exist, ceate directory 文件夹 2
    path2.mkdir()

finds = read_file(list_file)    # Read 列表.txt into a well-prepared list
files = search_files(path1)     # Search all files under 文件夹 1

"""
Match all files with items in 列表.txt
- matched files kept in result dictionary with key in 列表.txt
- Not-matched files kept in a list
"""
result = {}
for find in finds:
    result[find] = [file for file in files if file.stem == find]
not_found = [file for file in files if file.stem not in finds]

# Move all matched files into 文件夹 2
move_files(result, path2)

"""
Generate CSV report to 結果.csv
- All matched files for each item in 列表.txt
- All not-matched files for each item in 列表.txt
- Number of total files under 文件夹 1
- Number of files matched
- Number of files not matched
"""
text1 = 'Found for items in %s\n'%list_file.name
text2 = '\n\nNot found for items in %s\n'%list_file.name
for key, found in result.items():
    if found != []:
        text1 += ','.join([key]+list(map(str, found)))+'\n'
    else:
        text2 += key+'\n'
text3 = '\n\n%s Files in %s'%(str(len(files)), path1.name)
text4 = '\n%s Files in %s found'%(str(len(files)-len(not_found)), path1.name)
text5 = '\n%s Files in %s not found'%(str(len(not_found)), path1.name)
text = ''.join((text1, text2, text3, text4, text5))

with open(result_file, 'wt', encoding='utf8') as f:
    f.write(text)

print('Job finished and result file stored as %s'%str(result_file))
5年前 评论
fsfs (楼主) 5年前
fsfs (楼主) 5年前

非常感谢你的不断指点,可能是我的原因这边运行还是报错,我先研究懂你的思路和代码,在回来提问吧,我相信python是一门精彩的语言。

5年前 评论

import os
import shutil
path = 'C:/Users/Administrator/Desktop/列表.txt'
root = 'C:/Users/Administrator/Desktop/文件夹1'
root1 = 'C:/Users/Administrator/Desktop/文件夹2'
with open (path) as obj:
words = obj.readlines() for word in words:
for dirpath,dirnames,filenames in os.walk(root):
for filename in filenames:
if word.strip() == filename[0:-5]:
shutil.copy(root + "/" + filename,root1)
count = 0
for dirpath,dirnames,filepath in os.walk(root1): for f in filepath:
count += 1
print("复制成功数据: " + str(count) + "条")
os.system("pause") 通过重写以上代码已经实现了对照列表复制功能,我正在研究你入户如何生成csv报告,函数太多我脑袋有点乱呵呵,很感谢你的指点迷津

5年前 评论

很抱歉作为 版主没有及时回答你的问题,最近和朋友在开发推荐系统,学习算法。有时候进来社区看看文,改进改进几位小伙伴的文章格式、看看小伙伴们的文章,这两天有点忙,没有回复你 实在抱歉。加油!很多坑(哪怕再简单的问题)都是慢慢磨过了才懂,加油哦,万事开头难。👍👍👍👍

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!