使用python从文件中删除回车符
import os
import sys
files = os.listdir(sys.argv[1])
for file in files:
if file[-4:] == ".png":
os.rename(file, file.replace('\r', ''))
我使用上面的代码从文件名中删除 \r,但是当我执行时,我收到以下错误
Traceback (most recent call last):
File "renameImages.py", line 9, in <module>
os.rename(f, f.replace('\r', ''))
OSError: [Errno 2] No such file or directory
我哪里出错了?
import os
import sys
files = os.listdir(sys.argv[1])
for file in files:
if file[-4:] == ".png":
os.rename(file, file.replace('\r', ''))
Am using the above code to remove \r from the file name, but some how when I execute I get the following error
Traceback (most recent call last):
File "renameImages.py", line 9, in <module>
os.rename(f, f.replace('\r', ''))
OSError: [Errno 2] No such file or directory
Where am I going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有告诉它在 argv[1] 中声明的文件的目录
尝试 os.rename(sys.argv[1]+"/file",sys.argv[1]+"/"+replace('\r'','')
(或者对于 Windows 为“\\”)。
You didn't tell it the directory of the file, that was declared in
argv[1]
try
os.rename(sys.argv[1]+"/file",sys.argv[1]+"/"+replace('\r'','')
(or '\\' for Windows).
您可以使用 str.rstrip('\r') 方法从字符串右侧删除一组字符:
您在帖子中说文件名末尾有一个
\r
其中;这将是非常不寻常的。您确定您的文件名在字符串末尾有一个\r
,还是因为您使用 Python 来打印它而假设它有?请记住,Python 会将自动返回附加到您打印的字符串中。编辑
确定:文件名末尾确实有一个
\r
。我的第一个建议是修复生成此类不友好文件名的脚本...对于此脚本,您需要在前面添加目录名称或将 CD 插入相关目录。由于这个答案有前置,这里是 CD'ing:
You can use str.rstrip('\r') method to remove a set of characters from the right side of a string:
You say in your post that the file name has a
\r
at the end of it; this would be very unusual. Are you sure that your file name has a\r
at the end of the string or you are assuming it does because you used Python to print it? Remember that Python appends an automatic return to a string that you print.Edit
OK: the file name really has a
\r
on the end. My first recommendation is to fix the script that is producing such unfriendly file names...For this scipt, you need to either prepend the directory name on the front or CD into the relevant directory. Since THIS answer has the prepending, here is CD'ing: