简体   繁体   English

Python字符串串联和等效的bash参数扩展

[英]Python string concatenation and equivalent of bash parameter expansion

I'm kind of new to python, but something I find myself doing in bash a lot is prepending and appending strings to filenames with parameter expansion. 我是python的新手,但是我发现自己在bash中经常做的事情是使用参数扩展将字符串添加到文件名的前面和后面。

eg 例如

for file in *.txt ; do mkdir ${file%.*} ; mv $file ${file%.*}/ ; done

Would be an example for stripping off the extension of a load of files, making directories based on those names, and then moving the files inside their namesake folders now. 这将是一个示例,用于剥离文件的扩展名,基于这些名称创建目录,然后将文件移入其同名文件夹中。

If I want to achieve a similar thing, such as rename the output of a function based on the input file name (below is an example of a Biopython function), I've seen a few ways to do it with string concatenation etc, but without bracketing and so on, it looks confusing and like it might create parsing errors with spaces, quotes and so on being all over the place potentially. 如果我想实现类似的目的,例如根据输入文件名重命名函数的输出(以下是Biopython函数的示例),我已经看到了几种使用字符串串联的方法,但是没有括号等,它看起来很混乱,就像它可能会产生带有空格,引号等的解析错误一样。

SeqIO.convert(genbank, 'genbank', genbank[:-3]+'tmp', 'fasta')

There are other threads on here about using rsplit, string concatenation and so on, but is one of these more 'correct' than another? 这里还有其他有关使用rsplit,字符串连接等的线程,但是其中一个比另一个更“正确”吗?

String concatenation is really nice and works great in simple commands like print() , but when adding to commands that are expecting separated values, it strikes me as a little messy? 字符串连接确实很棒,并且在诸如print()类的简单命令中也能很好地工作,但是当添加到需要分隔值的命令中时,它会让我感到有些混乱吗?

You can use os.path.splitext which is build especially for file names: 您可以使用专门为文件名构建的os.path.splitext

>>> import os
>>> 
>>> fname = '/tmp/foo/bar.baz'
>>> sp = os.path.splitext(fname)
>>> sp
('/tmp/foo/bar', '.baz')

Extracting the name of the file without extension: 提取不带扩展名的文件名:

>>> os.path.basename(sp[0])
'bar'

And formatting a new file name: 并格式化一个新的文件名:

>>> "{}.txt".format(os.path.basename(sp[0]))
'bar.txt'

In general, when manipulating file names and paths I try to just use os.path , since it already handles edge cases, can normalize paths from things like /..//./././ , etc. 通常,在处理文件名和路径时,我尝试仅使用os.path ,因为它已经处理了/..//./././情况,因此可以规范/..//./././类的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM