我有一个包含许多行的文本文件。我需要在Python中向每行附加一个文本。
这是一个例子:
之前的文字:
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WallpaperManager wm = WallpaperManager.getInstance(this);
Drawable drawable = getResources().getDrawable(R.drawable.mydrawable);
Bitmap bitmap = drawableToBitmap(drawable);
Log.i(getClass().getName(), "bitmap = " +bitmap);
try {
wm.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "Wallpaper changed",
Toast.LENGTH_LONG).show();
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
修改了文字:
car
house
blog
答案 0 :(得分:1)
如果您只想在每一行上附加word
,这样就可以了。
file_name = 'YOUR_FILE_NAME.txt' #Put here your file
with open(file_name,'r') as fnr:
text = fnr.readlines()
text = "".join([line.strip() + ': [word]\n' for line in text])
with open(file_name,'w') as fnw:
fnw.write(text)
但是有很多方法可以做到这一点
答案 1 :(得分:0)
阅读列表中的文字:
f = open("filename.dat")
lines = f.readlines()
f.close()
追加文字:
new_lines = [x.strip() + "text_to_append" for x in lines]
# removes newlines from the elements of the list, appends
# the text for each element of the list in a list comprehension
编辑: 对于completness,一个更加pythonic的解决方案,将文本写入新文件:
with open('filename.dat') as f:
lines = f.readlines()
new_lines = [''.join([x.strip(), text_to_append, '\n']) for x in lines]
with open('filename_new.dat', 'w') as f:
f.writelines(new_lines)