Python 是否将.txt文件重命名为文件第一行用逗号分隔的值?
遵循这一思路: 我想出了这个代码:Python 是否将.txt文件重命名为文件第一行用逗号分隔的值?,python,csv,file-rename,Python,Csv,File Rename,遵循这一思路: 我想出了这个代码: import os for filename in os.listdir("."): if filename.endswith(".txt"): base, ext = os.path.splitext(filename) with open(filename, 'r') as infile: newname = infile.next().rstrip() newname += ext os.renam
import os
for filename in os.listdir("."):
if filename.endswith(".txt"):
base, ext = os.path.splitext(filename)
with open(filename, 'r') as infile:
newname = infile.next().rstrip()
newname += ext
os.rename(filename, newname)
这很好,但我真正需要的不是以整个第一行命名,而是以逗号之间的字符串命名。第一行用逗号(csv)分隔不同的值,我需要用第二个值重命名文件,即出现在第二个和第三个逗号之间的文本字符串
我发现了一个csv模块,但我不知道它是否有用或如何使用它。我发现我可以这样导入它:将unicodesv导入为csv
,以避免奇怪的字符问题
任何帮助都将不胜感激。
谢谢嗯
newname = infile.next().rstrip().split(",")[2]
也许吧?不确定从坦克到@Joran Beasley的问题很难判断它工作得很好,现在的代码是:
import os
for filename in os.listdir("."):
if filename.endswith(".csv"):
base, ext = os.path.splitext(filename)
with open(filename, 'r') as infile:
newname = infile.next().rstrip().split(",")[1]
newname += ""
os.rename(filename, newname)
谢谢你的快速回答,但它给了我这个
ValueError:I/O操作在关闭的文件上
hmmm,这让我觉得你实际上指的是第一个和第二个逗号之间,你不小心说了第二个和第三个逗号?