自动重命名CSV文件文件夹的代码出错

2024-10-02 22:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这段代码是用来自动重命名一堆被调用的CSV文件

history (1) ... history (42)

以下是事件列表: https://drive.google.com/open?id=0B5bJvxM9TZkhYXZOSnRDVnhTbFk

以下是“我的文件夹”中文件的屏幕截图:

screen shot

这些新名字是通过靓汤从网页中捕捉到的。新名称在格式上有两种可能大多数有two节,只有四个有three节。你知道吗

当谈到rename函数时,我遇到了一个error。你知道吗

以下是全部代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import os

events = open('events.txt', 'r')

os.chdir("C:\\Users\\Sayed\\Downloads")


# name
for event in events:
    sauce = urlopen(event).read()
    soup = BeautifulSoup(sauce, 'lxml')
    title = soup.find_all('title')
    for x in title:
        title = x.text

    try:
        firstName, lastNmame, country = (title.split('-'))
        firstName = firstName.strip()
        lastNmame = lastNmame.strip()
        country = country.strip()
        name = ('{} - {} - {}'.format(country, firstName, lastNmame))
        for file in os.listdir():
            firstName, ext = os.path.splitext(file)
            os.rename(firstName, name)

    except ValueError:
        pass
    try:
        firstName, country = (title.split('-'))
        firstName = firstName.strip()
        country = country.strip()
        name = ('{} - {}'.format(country, firstName))
        for file in os.listdir():
            firstName, ext = os.path.splitext(file)
            os.rename(firstName, name)

    except ValueError:
        pass

错误如下:

Traceback (most recent call last): 

 File "C:/Users/Sayed/PycharmProjects/Tutorial/pan.py", line 37, in <module>
    os.rename(firstName, name)

FileNotFoundError: [WinError 2] The system cannot find the file  specified: 'history  (1)' -> 'European Monetary Union - Services Sentiment'

Tags: 代码nameinimportfortitleosfirstname
1条回答
网友
1楼 · 发布于 2024-10-02 22:35:56

起作用了!

我复制了您的整个设置,包括所有history (x)文件和所有内容,并设法编写了有效的代码。你知道吗

在这里:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import os

events = open('events.txt', 'r')

os.chdir("C:\\Users\\Sayed\\Downloads")

for i, event in enumerate(events):
    sauce = urlopen(event).read()
    soup = BeautifulSoup(sauce, 'lxml')

    title = soup.find_all('title')[0].text.strip()

    filename = "history ({}).csv".format(i+1)

    newName = "{}.csv".format(title)

    os.rename(filename, newName)

它是如何工作的?

首先,我们像以前一样import所有必要的libraries。你知道吗

然后我们打开包含所有linksevents.txt文件到我们想要提取titles的页面。你知道吗

然后我们进入主for-loop。我们在这里循环的内容可能看起来有点奇怪,如果你以前没有见过的话,从技术上讲,我们从events中创建一个listtuples,其中tuple的第一个elementindex,第二个element是值,所以在这里,它是event。举个例子让你完全理解这一点:

>>> l = ["a", "b", "c", "d"]
>>> for i, ele in enumerate(l):
...     print(i, ele)
... 
0 a
1 b
2 c
3 d

所以现在,我们有两个variables要处理:在所有events中的event(因此link到页面)和index。请记住,由于Python lists是基于0的,index将从042(而不是143),因此当我们稍后使用它重命名files时,必须记住添加1。你知道吗

接下来,我们从link得到raw data,也就是eventurllib。然后,我们使用BeautifulSoupevent中提取title。这是通过查找页面中'title'所有并使用[0]索引第一个来实现的。我们需要index像这样soup.find_all返回长度list1element。然后我们用这个的.text得到一个string,然后在string上做一个.strip(),去掉回车符和换行符(/r/n)。你知道吗

接下来,我们定义一个名为variablefilename,它将存储我们当前想要renamefile的名称。我们得到name的方法是简单地取history (x).csv位,它对于所有的files都是相同的,并用我们正在处理的当前eventfile)的format位格式化,而不是i位作为files开始于history (1).csv而不是history (0).csv。你知道吗

然后我们定义一个名为newName的变量,它就是我们想要renamefilename。这个名字就是我们之前提取的name(The title),然后在末尾提取'.csv',因为我们需要保持fileextensions不变。你知道吗

最后,我们为这个file调用rename。这只是filenamenewName之间的关系!你知道吗


这肯定对我有用,所以我看不出有什么理由不适合你。。。另外,我希望你能理解代码正在做的每件事,只要在评论中问我是否遗漏了什么。。。你知道吗

相关问题 更多 >