我是python的新手,我有一个小脚本问题我希望有人能给我一个线索。
我有一个名为“one.txt”的文件,其中包含以下两行:
$args = array(
'post_type' => 'release', //remember this is-case sensitive
'posts_per_page' => -1,
);
$releaseQuery = new WP_Query( $args );
if ( $releaseQuery->have_posts() ) :
while ( $releaseQuery->have_posts() ) :
$releaseQuery->the_post();
// Fetching the post ID for demonstration and for use later
$c_id = get_the_ID();
// After running the_post(), alot of the Wordpress functions (not all) can now be used without supplying the post ID.
echo get_the_title();
// You could also have used get_the_title($c_id);
// Then:
echo get_post_meta($c_id, 'release_title', true);
echo get_post_meta($c_id, 'release_artist', true);
endwhile;
endif;
// Return to the current page's main query
wp_reset_query();
// This should now display the page's title
the_title();
我想在每行的末尾添加两个字符(“/ 1”)并将其写入另一个名为result.txt的文件中:
的Result.txt
Hello
Goodbye
我尝试了以下内容:
Hello1/
Goodbye1/
我得到了:
x=open("one.txt","r")
y=open("result.txt","w")
for line in x:
line2= "/1" +line
y.write(line2)
如果我改变line2:
1/Hello
1/Goodbye
我明白了:
line2= line + "/1"
也不正确
任何线索?
答案 0 :(得分:2)
您在阅读该行后忘记删除换行符,并在写入之前将其重新添加。
答案 1 :(得分:1)
这是另一个版本,使用文件的上下文管理器(所以你不要忘记稍后关闭它们) - 否则它类似于@IgorPomaranskiy的回答:
with open("one.txt") as x, open("result.txt", "w") as y:
for line in x:
y.write("{}\n".format(line.strip() + "/1"))
答案 2 :(得分:0)
x = open("one.txt", "r")
y = open("result.txt", "w")
for line in x:
y.write("{}/1\n".format(line.strip())
答案 3 :(得分:0)
当您从文件中读取一行时,该字符串包含指示该行末尾的换行符。您的字符串不是"Hello"
,而是"Hello\n"
。您需要删除该换行符,创建输出字符串,并在将其写回时添加另一个换行符。
for line in x:
line = line.rstrip('\n')
line2 = line + '/1\n'
y.write(line2)